<?php

namespace App\Http\Controllers\Web\Payroll;

use App\Http\Controllers\Controller;
use App\Models\CompanySetting;
use Illuminate\Http\Request;

class PayrollSettingsController extends Controller
{
    private function companyId(): ?int
    {
        return auth()->user()?->company_id;
    }

    private function getPayrollSetting(string $key, $default = null)
    {
        if (! $this->companyId()) {
            return $default;
        }
        $s = CompanySetting::withoutGlobalScopes()->where('company_id', $this->companyId())->where('key', $key)->first();

        return $s ? $s->value : $default;
    }

    private function setPayrollSetting(string $key, ?string $value): void
    {
        if (! $this->companyId()) {
            return;
        }
        CompanySetting::withoutGlobalScopes()->updateOrCreate(
            ['company_id' => $this->companyId(), 'key' => $key],
            ['value' => $value ?? '']
        );
    }

    public function settingsIndex()
    {
        $settings = [
            'payroll_pf_enabled' => $this->getPayrollSetting('payroll_pf_enabled', '0'),
            'pf_excluded_in_ctc' => $this->getPayrollSetting('pf_excluded_in_ctc', '0'),
            'payroll_pf_rate' => $this->getPayrollSetting('payroll_pf_rate', '12'),
            'payroll_pf_cap' => $this->getPayrollSetting('payroll_pf_cap', '15000'),
            'payroll_esi_enabled' => $this->getPayrollSetting('payroll_esi_enabled', '0'),
            'esi_excluded_in_ctc' => $this->getPayrollSetting('esi_excluded_in_ctc', '0'),
            'payroll_esi_rate' => $this->getPayrollSetting('payroll_esi_rate', '0.75'),
            'payroll_esi_cap' => $this->getPayrollSetting('payroll_esi_cap', '21000'),
            'payroll_pt_enabled' => $this->getPayrollSetting('payroll_pt_enabled', '0'),
            'payroll_pt_amount' => $this->getPayrollSetting('payroll_pt_amount', '200'),
        ];

        return view('payroll.settings', compact('settings'));
    }

    public function settingsStore(Request $request)
    {
        $request->validate([
            'payroll_currency' => 'nullable|string|max:10',
            'payroll_pay_day' => 'nullable',
            'payroll_rounding_mode' => 'nullable|in:nearest_rupee,nearest_0_05',
            'payroll_lop_basis' => 'nullable|in:gross,basic,earned_gross',
            'payroll_working_days_source' => 'nullable|in:weekday_minus_holidays,shift_calendar',
            'payroll_declaration_window_enabled' => 'nullable|in:0,1',
            'declaration_from_day' => 'nullable|integer|min:1|max:31',
            'declaration_to_day' => 'nullable|integer|min:1|max:31',
            'declaration_year_from' => 'nullable|date',
            'declaration_year_to' => 'nullable|date',
            'proof_mandatory' => 'nullable|in:0,1',
            'payroll_tds_enabled' => 'nullable|in:0,1',
            'income_tax_plan_old_id' => 'nullable|integer|min:0',
            'income_tax_plan_new_id' => 'nullable|integer|min:0',
            'payout_mode' => 'nullable|in:bank_transfer,cash',
            'payout_requires_approval' => 'nullable|in:0,1',
            'show_employer_contrib' => 'nullable|in:0,1',
            'show_ytd_totals' => 'nullable|in:0,1',
            'show_leave_balance' => 'nullable|in:0,1',
            'payroll_pf_enabled' => 'nullable|in:0,1',
            'pf_excluded_in_ctc' => 'nullable|in:0,1',
            'payroll_pf_rate' => 'nullable|numeric|min:0|max:100',
            'payroll_pf_cap' => 'nullable|numeric|min:0',
            'payroll_esi_enabled' => 'nullable|in:0,1',
            'esi_excluded_in_ctc' => 'nullable|in:0,1',
            'payroll_esi_rate' => 'nullable|numeric|min:0|max:100',
            'payroll_esi_cap' => 'nullable|numeric|min:0',
            'payroll_pt_enabled' => 'nullable|in:0,1',
            'payroll_pt_amount' => 'nullable|numeric|min:0',
            'redirect_to' => 'nullable|string',
        ]);

        if ($request->has('payroll_currency')) {
            $this->setPayrollSetting('payroll_currency', $request->input('payroll_currency', 'INR'));
        }
        if ($request->has('payroll_pay_day')) {
            $this->setPayrollSetting('payroll_pay_day', (string) $request->input('payroll_pay_day', 'last_day'));
        }
        if ($request->has('payroll_rounding_mode')) {
            $this->setPayrollSetting('payroll_rounding_mode', (string) $request->input('payroll_rounding_mode', 'nearest_rupee'));
        }
        if ($request->has('payroll_lop_basis')) {
            $this->setPayrollSetting('payroll_lop_basis', (string) $request->input('payroll_lop_basis', 'gross'));
        }
        if ($request->has('payroll_working_days_source')) {
            $this->setPayrollSetting('payroll_working_days_source', (string) $request->input('payroll_working_days_source', 'weekday_minus_holidays'));
        }
        if ($request->has('payroll_declaration_window_enabled')) {
            $this->setPayrollSetting('payroll_declaration_window_enabled', $request->input('payroll_declaration_window_enabled', '0'));
        }
        if ($request->has('declaration_from_day')) {
            $this->setPayrollSetting('declaration_from_day', (string) $request->input('declaration_from_day', 1));
        }
        if ($request->has('declaration_to_day')) {
            $this->setPayrollSetting('declaration_to_day', (string) $request->input('declaration_to_day', 25));
        }
        if ($request->has('declaration_year_from')) {
            $this->setPayrollSetting('declaration_year_from', (string) $request->input('declaration_year_from', ''));
        }
        if ($request->has('declaration_year_to')) {
            $this->setPayrollSetting('declaration_year_to', (string) $request->input('declaration_year_to', ''));
        }
        if ($request->has('proof_mandatory')) {
            $this->setPayrollSetting('proof_mandatory', (string) $request->input('proof_mandatory', '0'));
        }
        if ($request->has('payroll_tds_enabled')) {
            $this->setPayrollSetting('payroll_tds_enabled', (string) $request->input('payroll_tds_enabled', '0'));
        }
        if ($request->has('income_tax_plan_old_id')) {
            $this->setPayrollSetting('income_tax_plan_old_id', (string) $request->input('income_tax_plan_old_id', ''));
        }
        if ($request->has('income_tax_plan_new_id')) {
            $this->setPayrollSetting('income_tax_plan_new_id', (string) $request->input('income_tax_plan_new_id', ''));
        }
        if ($request->has('payout_mode')) {
            $this->setPayrollSetting('payout_mode', (string) $request->input('payout_mode', 'bank_transfer'));
        }
        if ($request->has('payout_requires_approval')) {
            $this->setPayrollSetting('payout_requires_approval', (string) $request->input('payout_requires_approval', '0'));
        }
        if ($request->has('show_employer_contrib')) {
            $this->setPayrollSetting('show_employer_contrib', (string) $request->input('show_employer_contrib', '0'));
        }
        if ($request->has('show_ytd_totals')) {
            $this->setPayrollSetting('show_ytd_totals', (string) $request->input('show_ytd_totals', '0'));
        }
        if ($request->has('show_leave_balance')) {
            $this->setPayrollSetting('show_leave_balance', (string) $request->input('show_leave_balance', '0'));
        }
        $this->setPayrollSetting('payroll_pf_enabled', $request->input('payroll_pf_enabled', '0'));
        $this->setPayrollSetting('pf_excluded_in_ctc', $request->input('pf_excluded_in_ctc', '0'));
        $this->setPayrollSetting('payroll_pf_rate', $request->input('payroll_pf_rate', '12'));
        $this->setPayrollSetting('payroll_pf_cap', $request->input('payroll_pf_cap', '15000'));
        $this->setPayrollSetting('payroll_esi_enabled', $request->input('payroll_esi_enabled', '0'));
        $this->setPayrollSetting('esi_excluded_in_ctc', $request->input('esi_excluded_in_ctc', '0'));
        $this->setPayrollSetting('payroll_esi_rate', $request->input('payroll_esi_rate', '0.75'));
        $this->setPayrollSetting('payroll_esi_cap', $request->input('payroll_esi_cap', '21000'));
        $this->setPayrollSetting('payroll_pt_enabled', $request->input('payroll_pt_enabled', '0'));
        $this->setPayrollSetting('payroll_pt_amount', $request->input('payroll_pt_amount', '200'));
        $redirectTo = $request->input('redirect_to');

        return redirect($redirectTo ?: route('payroll.index', ['tab' => 'setup', 'sub' => 'pf_esi']))->with('success', 'Payroll settings saved.');
    }
}
