<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Law;
use App\Models\Volum;
use Illuminate\Http\Request;

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

        if ($request->filled('q')) {
            $query->where('title', 'like', '%' . $request->q . '%');
        }

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

        return view('admin.volum.index', compact('volums'));
    }

    public function create()
    {
        $laws = Law::all();

        return view('admin.volum.create', compact('laws'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'title' => 'required',
            'number' => 'required',
            'law_id' => 'required',
        ]);

        volum::query()->create($validated);

        return redirect(route('volum.index'));
    }

    public function edit(Volum $volum)
    {
        $laws = Law::all();

        return view('admin.volum.update', compact('volum', 'laws'));
    }

    public function update(Request $request, Volum $volum)
    {
        $validated = $request->validate([
            'title' => 'required',
            'number' => 'required',
            'law_id' => 'required',
        ]);

        $volum->update($validated);

        return redirect(route('volum.index'));
    }

    public function destroy(Volum $volum)
    {
        $volum->delete();

        return redirect(route('volum.index'));
    }
}
