<?php

namespace App\Http\Controllers\Admin;

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

class CategoryController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = Category::get();
            return datatables($query)->toJson();
        }
        return view('admin.category.index');
    }


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {

        $lastCategoryIndex = Category::max('display_order');
        $lastCategoryIndex = $lastCategoryIndex ? $lastCategoryIndex + 1 : 1;
        return view('admin.category.create', compact('lastCategoryIndex'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $attributes = $request->validate([
            'name' => 'required|string|max:100',
            'display_order' => 'required|integer|unique:categories,display_order',
            'img' => 'nullable|string|max:255',
        ]);

        Category::create($attributes);

        return to_route('categories.index')->with('success', __('trans.alert.success.done_create', ['name' => 'Category']));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Category $category)
    {
        return view('admin.category.edit', compact('category'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, Category $category)
    {
        $attributes = $request->validate([
            'name' => 'required|string|max:100',
            'display_order' => 'required|integer',
            'img' => 'nullable|string|max:255',
        ]);

        $category->update($attributes);

        return to_route('categories.index')->with('success', __('trans.alert.success.done_update', ['name' => 'Category']));
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Category $category)
    {
        $category->delete();
        return to_route('categories.index')->with('success', __('trans.alert.success.done_delete', ['name' => 'Category']));
    }
}
