<?php

namespace App\Http\Controllers\Admin;

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

class TaxController extends Controller
{
    public function index()
    {
        $taxes = Tax::with(['slabs', 'creator'])->latest()->get();
        $taxSetup = TaxSetup::current()->load('activeTax');

        return Inertia::render('Admin/Tax/Index', [
            'taxes' => $taxes,
            'taxSetup' => [
                'is_enabled' => $taxSetup->is_enabled,
                'active_tax_id' => $taxSetup->active_tax_id,
            ],
        ]);
    }

    public function create()
    {
        return Inertia::render('Admin/Tax/CreateEdit');
    }

    public function edit(Tax $tax)
    {
        $tax->load('slabs');

        return Inertia::render('Admin/Tax/CreateEdit', [
            'tax' => $tax,
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => ['required', Rule::in(['fixed', 'slab'])],
            'status' => ['required', Rule::in(['active', 'inactive'])],
            'fixed_amount' => 'nullable|required_if:type,fixed|numeric|min:0',
            'fixed_amount_type' => ['nullable', 'required_if:type,fixed', Rule::in(['percentage', 'fixed'])],
            'slabs' => 'nullable|array|required_if:type,slab',
            'slabs.*.min_income' => 'required|numeric|min:0',
            'slabs.*.max_income' => 'nullable|numeric|gt:slabs.*.min_income',
            'slabs.*.percentage' => 'required|numeric|min:0|max:100',
        ]);

        $tax = Tax::create([
            'name' => $validated['name'],
            'type' => $validated['type'],
            'fixed_amount' => $validated['fixed_amount'] ?? null,
            'fixed_amount_type' => $validated['fixed_amount_type'] ?? null,
            'status' => $validated['status'],
            'created_by' => $request->user()->id,
        ]);

        if ($validated['type'] === 'slab' && ! empty($validated['slabs'])) {
            foreach ($validated['slabs'] as $slab) {
                $tax->slabs()->create([
                    'min_income' => $slab['min_income'],
                    'max_income' => $slab['max_income'] ?? null,
                    'percentage' => $slab['percentage'],
                ]);
            }
        }

        return redirect()->route('admin.taxes.index')->with('success', 'Tax configuration created successfully.');
    }

    public function update(Request $request, Tax $tax)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'type' => ['required', Rule::in(['fixed', 'slab'])],
            'status' => ['required', Rule::in(['active', 'inactive'])],
            'fixed_amount' => 'nullable|required_if:type,fixed|numeric|min:0',
            'fixed_amount_type' => ['nullable', 'required_if:type,fixed', Rule::in(['percentage', 'fixed'])],
            'slabs' => 'nullable|array|required_if:type,slab',
            'slabs.*.id' => 'nullable|exists:tax_slabs,id',
            'slabs.*.min_income' => 'required|numeric|min:0',
            'slabs.*.max_income' => 'nullable|numeric|gt:slabs.*.min_income',
            'slabs.*.percentage' => 'required|numeric|min:0|max:100',
        ]);

        $tax->update([
            'name' => $validated['name'],
            'type' => $validated['type'],
            'fixed_amount' => $validated['fixed_amount'] ?? null,
            'fixed_amount_type' => $validated['fixed_amount_type'] ?? null,
            'status' => $validated['status'],
        ]);

        if ($validated['type'] === 'slab') {
            $existingSlabIds = [];
            if (! empty($validated['slabs'])) {
                foreach ($validated['slabs'] as $slab) {
                    if (isset($slab['id'])) {
                        $tax->slabs()->where('id', $slab['id'])->update([
                            'min_income' => $slab['min_income'],
                            'max_income' => $slab['max_income'] ?? null,
                            'percentage' => $slab['percentage'],
                        ]);
                        $existingSlabIds[] = $slab['id'];
                    } else {
                        $newSlab = $tax->slabs()->create([
                            'min_income' => $slab['min_income'],
                            'max_income' => $slab['max_income'] ?? null,
                            'percentage' => $slab['percentage'],
                        ]);
                        $existingSlabIds[] = $newSlab->id;
                    }
                }
            }
            // Delete slabs that were removed in the UI
            $tax->slabs()->whereNotIn('id', $existingSlabIds)->delete();
        } else {
            // If switched from slab to fixed, delete all slabs
            $tax->slabs()->delete();
        }

        return redirect()->route('admin.taxes.index')->with('success', 'Tax configuration updated successfully.');
    }

    public function destroy(Tax $tax)
    {
        if ($tax->assignments()->exists()) {
            return back()->with('error', 'Cannot delete a tax that is assigned to employees.');
        }

        $tax->delete();

        return back()->with('success', 'Tax configuration deleted.');
    }
}
