<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tax;
use App\Models\TaxSetup;
use Illuminate\Http\Request;

class TaxSetupController extends Controller
{
    public function update(Request $request)
    {
        $validated = $request->validate([
            'is_enabled' => 'required|boolean',
            'active_tax_id' => 'nullable|exists:taxes,id',
        ]);

        // If enabling, require an active tax to be chosen
        if ($validated['is_enabled'] && empty($validated['active_tax_id'])) {
            return back()->withErrors(['active_tax_id' => 'Please select a tax policy to enable tax deduction.']);
        }

        $setup = TaxSetup::current();

        $setup->update([
            'is_enabled' => $validated['is_enabled'],
            'active_tax_id' => $validated['is_enabled'] ? $validated['active_tax_id'] : null,
            'updated_by' => $request->user()->id,
        ]);

        return back()->with('success', $validated['is_enabled']
            ? 'Income tax enabled with the selected policy.'
            : 'Income tax has been disabled.'
        );
    }
}
