<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Category;
use Illuminate\Http\Request;

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

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

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

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

    public function create()
    {
        return view('admin.categories.create');
    }

    public function store(Request $request)
    {
        $validated  = $request->validate([
            'name' => 'required',
            'type' => 'required'
        ]);


        Category::create($validated);

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

    public function edit(Category $category)
    {
        return view('admin.categories.update',compact('category'));
    }

    public function update(Request $request, Category $category)
    {
        $validated  = $request->validate([
            'name' => 'required',
            'type' => 'required'
        ]);

        $category->update($validated);
        
        return redirect(route('categories.index'));
    }

    public function destroy(Category $category)
    {
        $category->delete();
    
        return redirect(route('categories.index'));
    }
}
