<?php

namespace App\Http\Controllers\Backend;

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

class ProductCategoryController extends Controller
{
    public function index(Request $request)
    {
        $title = 'Account product categories';
        $query = ProductCategory::withCount('products')->orderBy('sort');
        if ($request->filled('search')) {
            $term = $request->search;
            $query->where('name', 'like', "%{$term}%");
        }
        $categories = $query->paginate(10)->withQueryString();
        $search = $request->search ?? '';
        return view('backend.products.categories.index', compact('title', 'categories', 'search'));
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|in:0,1',
        ]);
        ProductCategory::create([
            'name' => $request->name,
            'sort' => $request->sort ?? 0,
            'status' => (bool) ($request->status ?? 1),
        ]);
        return redirect()->back()->with('success', 'Category added.');
    }

    public function update(Request $request, $id)
    {
        $cat = ProductCategory::findOrFail($id);
        $request->validate([
            'name' => 'required|string|max:255',
            'sort' => 'nullable|integer|min:0',
            'status' => 'nullable|in:0,1',
        ]);
        $cat->update([
            'name' => $request->name,
            'sort' => $request->sort ?? 0,
            'status' => (bool) ($request->status ?? 1),
        ]);
        return redirect()->back()->with('success', 'Category updated.');
    }

    public function destroy($id)
    {
        ProductCategory::findOrFail($id)->delete();
        return redirect()->back()->with('success', 'Category deleted.');
    }
}
