<?php

namespace App\Http\Controllers\Admin;

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

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

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

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

        return view('admin.chapter.index', compact('chapters'));
    }

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

        return view('admin.chapter.create', compact('sections', 'books', 'volums', 'laws','divisions'));
    }

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

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

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

    public function edit(Chapter $chapter)
    {
        $sections = Section::all();
        $books = Book::all();
        $volums = Volum::all();
        $laws = Law::all();
        $divisions = Division::all();

        return view('admin.chapter.update', compact('sections', 'chapter', 'books', 'volums', 'laws','divisions'));
    }

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

        $chapter->update($validated);

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

    public function destroy(Chapter $chapter)
    {
        $chapter->delete();

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