<?php

namespace App\Http\Controllers;

use App\Models\Tax;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class TaxController extends Controller
{
    public function index(Request $request)
    {
        try {
            $query = Tax::query();

            if ($request->has('search')) {
                $search = $request->input('search');
                $query->where('name', 'like', "%{$search}%")
                      ->orWhere('rate', 'like', "%{$search}%");
            }

            $taxes = $query->orderBy('name')->paginate(20);

            return view('taxes.index', compact('taxes'));
            
        } catch (\Exception $e) {
            Log::error('Tax index error: ' . $e->getMessage());
            return redirect()->route('dashboard')
                ->with('error', 'Failed to load taxes.');
        }
    }

    public function create()
    {
        return view('taxes.create');
    }

    public function store(Request $request)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'rate' => 'required|numeric|min:0|max:100',
                'description' => 'nullable|string|max:500',
                'is_active' => 'boolean',
            ]);

            $validated['is_active'] = $request->has('is_active');

            Tax::create($validated);

            return redirect()->route('taxes.index')
                ->with('success', 'Tax created successfully.');
                
        } catch (\Exception $e) {
            Log::error('Tax store error: ' . $e->getMessage());
            return redirect()->back()
                ->with('error', 'Failed to create tax.')
                ->withInput();
        }
    }

    public function show(Tax $tax)
    {
        return view('taxes.show', compact('tax'));
    }

    public function edit(Tax $tax)
    {
        return view('taxes.edit', compact('tax'));
    }

    public function update(Request $request, Tax $tax)
    {
        try {
            $validated = $request->validate([
                'name' => 'required|string|max:255',
                'rate' => 'required|numeric|min:0|max:100',
                'description' => 'nullable|string|max:500',
                'is_active' => 'boolean',
            ]);

            $validated['is_active'] = $request->has('is_active');

            $tax->update($validated);

            return redirect()->route('taxes.index')
                ->with('success', 'Tax updated successfully.');
                
        } catch (\Exception $e) {
            Log::error('Tax update error: ' . $e->getMessage());
            return redirect()->back()
                ->with('error', 'Failed to update tax.')
                ->withInput();
        }
    }

    public function destroy(Tax $tax)
    {
        try {
            // Check if tax is used by products
            if ($tax->products()->exists()) {
                return redirect()->route('taxes.index')
                    ->with('error', 'Cannot delete tax that is assigned to products.');
            }

            $tax->delete();

            return redirect()->route('taxes.index')
                ->with('success', 'Tax deleted successfully.');
                
        } catch (\Exception $e) {
            Log::error('Tax destroy error: ' . $e->getMessage());
            return redirect()->route('taxes.index')
                ->with('error', 'Failed to delete tax.');
        }
    }

    public function search(Request $request)
    {
        try {
            $search = $request->input('q');
            $taxes = Tax::where('name', 'like', "%{$search}%")
                ->orWhere('rate', 'like', "%{$search}%")
                ->where('is_active', true)
                ->limit(10)
                ->get(['id', 'name', 'rate']);

            return response()->json($taxes);
        } catch (\Exception $e) {
            Log::error('Tax search error: ' . $e->getMessage());
            return response()->json([], 500);
        }
    }
}