<?php

namespace App\Http\Controllers\Admin;

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

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

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

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

        return view('admin.book.index', compact('books'));
    }

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

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

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

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

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

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

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

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

        $book->update($validated);

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

    public function destroy(Book $book)
    {
        $book->delete();

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