<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Tax;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class TaxController extends Controller
{
    /**
     * Display a listing of taxes.
     */
    public function index(): Response
    {
        return Inertia::render('Admin/Taxes/Index', [
            'taxes' => Tax::ordered()->get(),
        ]);
    }

    /**
     * Show the form for creating a new tax.
     */
    public function create(): Response
    {
        return Inertia::render('Admin/Taxes/Form', [
            'tax' => null,
        ]);
    }

    /**
     * Store a newly created tax.
     */
    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'code' => 'required|string|max:20|unique:taxes,code',
            'rate' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string|max:255',
            'is_active' => 'boolean',
            'is_compound' => 'boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        Tax::create($validated);

        return redirect()->route('admin.taxes.index')
            ->with('success', 'Impuesto creado correctamente.');
    }

    /**
     * Show the form for editing a tax.
     */
    public function edit(Tax $tax): Response
    {
        return Inertia::render('Admin/Taxes/Form', [
            'tax' => $tax,
        ]);
    }

    /**
     * Update the specified tax.
     */
    public function update(Request $request, Tax $tax): RedirectResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'code' => 'required|string|max:20|unique:taxes,code,' . $tax->id,
            'rate' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string|max:255',
            'is_active' => 'boolean',
            'is_compound' => 'boolean',
            'order' => 'nullable|integer|min:0',
        ]);

        $tax->update($validated);

        return redirect()->route('admin.taxes.index')
            ->with('success', 'Impuesto actualizado correctamente.');
    }

    /**
     * Remove the specified tax.
     */
    public function destroy(Tax $tax): RedirectResponse
    {
        $tax->delete();

        return redirect()->route('admin.taxes.index')
            ->with('success', 'Impuesto eliminado correctamente.');
    }

    /**
     * Toggle tax active status.
     */
    public function toggle(Tax $tax): RedirectResponse
    {
        $tax->update(['is_active' => !$tax->is_active]);

        return back()->with('success', 
            $tax->is_active 
                ? 'Impuesto activado.' 
                : 'Impuesto desactivado.'
        );
    }
}
