<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\TaxRate;
use Illuminate\Http\Request;

class TaxRateController extends Controller
{
    public function index()
    {
        $taxRates = TaxRate::orderBy('state_name')->get();
        return view('admin.tax-rates.index', compact('taxRates'));
    }

    public function create()
    {
        return view('admin.tax-rates.create');
    }

    public function edit(TaxRate $taxRate)
    {
        return view('admin.tax-rates.edit', compact('taxRate'));
    }

public function store(Request $request)
{
    try {
        $validated = $request->validate([
            'state_name' => 'required|string|max:255|unique:tax_rates',
            'state_code' => 'required|string|max:10',
            'rate' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string',
            'country_code' => 'required|string|max:10',
            'country' => 'required|string|max:255'
        ]);

        // Handle the active status separately
        $validated['active'] = $request->has('active');

        TaxRate::create($validated);

        return redirect()->route('admin.tax-rates.index')
            ->with('success', 'Tax rate added successfully');
    } catch (\Exception $e) {
        return back()
            ->withInput()
            ->withErrors(['error' => 'Failed to create tax rate. ' . $e->getMessage()]);
    }
}


public function update(Request $request, TaxRate $taxRate)
{
    try {
        $validated = $request->validate([
            'state_name' => 'required|string|max:255|unique:tax_rates,state_name,' . $taxRate->id,
            'state_code' => 'required|string|max:10',
            'rate' => 'required|numeric|min:0|max:100',
            'description' => 'nullable|string',
            'country_code' => 'required|string|max:10',
            'country' => 'required|string|max:255'
        ]);

        // Handle the active status separately
        $validated['active'] = $request->has('active');

        $taxRate->update($validated);

        return redirect()->route('admin.tax-rates.index')
            ->with('success', 'Tax rate updated successfully');
    } catch (\Exception $e) {
        return back()
            ->withInput()
            ->withErrors(['error' => 'Failed to update tax rate. ' . $e->getMessage()]);
    }
}


public function destroy(TaxRate $taxRate)
    {
        $taxRate->delete();
        return redirect()->route('admin.tax-rates.index')
            ->with('success', 'Tax rate deleted successfully');
    }






}