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

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

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

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

        return view('admin.part.index', compact('parts'));
    }

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

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

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

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

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

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

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

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

        $part->update($validated);

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

    public function destroy(Part $part)
    {
        $part->delete();

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