<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Book;
use App\Models\Branch;
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 BranchController extends Controller
{
    public function index(Request $request)
    {
        $query = Branch::query();

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

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

        return view('admin.branch.index', compact('branchs'));
    }

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

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

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

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

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

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

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

    public function update(Request $request, Branch $branch)
    {

        $validated = $request->validate([
            'title' => 'required',
                'number' => 'required',
            'chapter_id' => 'nullable',
            'part_id' => 'nullable',
            'gate_id' => 'nullable',
            'section_id' => 'nullable',
            'book_id' => 'nullable',
            'volum_id' => 'required',
            'law_id' => 'required',
            'division_id' => 'nullable',
        ]);

        $branch->update($validated);

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

    public function destroy(Branch $branch)
    {
        $branch->delete();

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