<?php

namespace App\Http\Controllers\Admin;

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

class JudicialPrecedentCategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $query = JudicialPrecedentCategory::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.judicial-precedent-category.index', compact('categories'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        return view('admin.judicial-precedent-category.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|unique:judicial_precedent_categories,name'
        ]);

        JudicialPrecedentCategory::create($validated);

        return redirect(route('judicial-precedent-category.index'));
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(JudicialPrecedentCategory $judicialPrecedentCategory)
    {
        return view('admin.judicial-precedent-category.update', compact('judicialPrecedentCategory'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, JudicialPrecedentCategory $judicialPrecedentCategory)
    {
        $validated = $request->validate([
            'name' => 'required|string|unique:judicial_precedent_categories,name,' . $judicialPrecedentCategory->id
        ]);

        $judicialPrecedentCategory->update($validated);

        return redirect(route('judicial-precedent-category.edit', $judicialPrecedentCategory->id));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(JudicialPrecedentCategory $judicialPrecedentCategory)
    {
        $judicialPrecedentCategory->delete();
        return redirect(route('judicial-precedent-category.index'));
    }
}
