<?php

namespace App\Http\Controllers\Admin;

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

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

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

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

        return view('admin.division.index', compact('divisions'));
    }

    public function create()
    {
        $books = Book::all();
        $volums = Volum::all();
        $laws = Law::all();

        return view('admin.division.create', compact('books', 'volums', 'laws'));
    }

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

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

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

    public function edit(division $division)
    {
        $books = Book::all();
        $volums = Volum::all();
        $laws = Law::all();

        return view('admin.division.update', compact('division','books', 'volums', 'laws'));
    }

    public function update(Request $request, Division $division)
    {

        $validated = $request->validate([
            'title' => 'required',
            'number' => 'required',
            'book_id' => 'nullable',
            'volum_id' => 'required',
            'law_id' => 'required',
        ]);

        $division->update($validated);

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

    public function destroy(Division $division)
    {
        $division->delete();

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