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

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

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

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

        return view('admin.gate.index', compact('gates'));
    }

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

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

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

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

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

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

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

    public function update(Request $request, Gate $gate)
    {
        $validated = $request->validate([
            'title' => 'required',
            'number' => 'required',
            'part_id' => 'nullable',
            'division_id' => 'nullable',
        ]);

        $gate->update($validated);

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

    public function destroy(Gate $gate)
    {
        $gate->delete();

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