<?php

namespace App\Http\Controllers\Admin;

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

class LegalOpinionCategoryController extends Controller
{
    public function index(Request $request)
    {
        $query = LegalOpinionCategory::query();

        if ($request->filled('q')) {
            $q = $request->q;
            $query->where('name', 'like', "%{$q}%");
        }

        $perPage = min(max((int) $request->input('per_page', 15), 10), 100);
        $categories = $query->paginate($perPage)->withQueryString();

        return view('admin.legal-opinion-category.index', compact('categories'));
    }

    public function create()
    {
        return view('admin.legal-opinion-category.create');
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|unique:legal_opinion_categories,name',
        ]);

        LegalOpinionCategory::create($validated);

        return redirect(route('legal-opinion-category.index'));
    }

    public function edit(LegalOpinionCategory $legalOpinionCategory)
    {
        return view('admin.legal-opinion-category.update', compact('legalOpinionCategory'));
    }

    public function show(LegalOpinionCategory $legalOpinionCategory)
    {
        return redirect(route('legal-opinion-category.edit', $legalOpinionCategory->id));
    }

    public function update(Request $request, LegalOpinionCategory $legalOpinionCategory)
    {
        $validated = $request->validate([
            'name' => 'required|string|unique:legal_opinion_categories,name,' . $legalOpinionCategory->id,
        ]);

        $legalOpinionCategory->update($validated);

        return redirect(route('legal-opinion-category.edit', $legalOpinionCategory->id));
    }

    public function destroy(LegalOpinionCategory $legalOpinionCategory)
    {
        $legalOpinionCategory->delete();

        return redirect(route('legal-opinion-category.index'));
    }
}
