<?php

namespace App\Http\Controllers;

use App\Models\Tax;
use Exception;
use Illuminate\Http\Request;

class TaxController extends Controller
{
    // Show tax form and tax records
    public function createTax()
    {
        $taxes = Tax::all();
        return view('maintanance.chart_of_accounts.create_tax', compact('taxes'));
    }

    // Store new tax
    public function storeTax(Request $request)
    {
        try {
            $request->validate([
                'description' => 'required|string|max:255|unique:taxes,description',
                'rate' => 'required|numeric|min:0',
            ], [
                'description.unique' => 'The description already exists. Please choose a different one.',
            ]);

            $tax = new Tax();
            $tax->description = $request->description;
            $tax->rate = $request->rate;
            $tax->save();

            return redirect()->route('tax.create')->with('success', 'Tax created successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Edit tax
    public function editTax(Request $request)
    {
        try {
            $request->validate([
                'id' => 'required|integer|exists:taxes,id',
                'description' => 'required|string|max:255',
                'rate' => 'required|numeric|min:0',
            ]);

            $tax = Tax::findOrFail($request->id);
            $tax->description = $request->description;
            $tax->rate = $request->rate;
            $tax->save();

            return redirect()->route('tax.create')->with('success', 'Tax updated successfully.');
        } catch (Exception $e) {
            return redirect()->back()->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }

    // Delete tax
    public function deleteTax($id)
    {
        try {
            $tax = Tax::findOrFail($id);
            $tax->delete();

            return redirect()->route('tax.create')->with('success', 'Tax deleted successfully.');
        } catch (Exception $e) {
            return redirect()->route('tax.create')->withErrors(['error' => 'An error occurred: ' . $e->getMessage()]);
        }
    }
}
