<?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\Section;
use App\Models\Volum;
use Illuminate\Http\Request;

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

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

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

        return view('admin.section.index', compact('sections'));
    }

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

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

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

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

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

    public function edit(Section $section)
    {
        $books = Book::all();
        $volums = Volum::all();
        $laws = Law::all();
        $sections = Section::all();
        $divisions = Division::all();
        
        return view('admin.section.update', compact('section', 'books', 'volums', 'laws','sections','divisions'));
    }

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

        $section->update($validated);

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

    public function destroy(Section $section)
    {
        $section->delete();

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