<?php

namespace App\Http\Controllers;

use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class CategoryController extends Controller
{
    /**
     * GET /products/categories
     * Route name: products.categories.index
     */
    public function index(Request $request)
    {
        $q = trim($request->get('q', ''));

        $categories = Category::query()
            ->when($q, function ($qr) use ($q) {
                $qr->where(function ($w) use ($q) {
                    $w->where('name', 'like', "%{$q}%")
                      ->orWhere('code', 'like', "%{$q}%");
                });
            })
            ->orderByDesc('id')
            ->paginate(20)
            ->withQueryString();

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

    /**
     * GET /products/categories/create
     * Route name: products.categories.create
     */
    public function create()
    {
        return view('products.categories.create');
    }

    /**
     * POST /products/categories
     * Route name: products.categories.store
     */
    public function store(Request $request)
    {
        $data = $request->validate([
            'name'   => ['required', 'string', 'max:191', 'unique:rm_categories,name'],
            'code'   => ['nullable', 'string', 'max:191'],
            'status' => ['required', Rule::in(['0','1',0,1,true,false])],
        ]);

        Category::create([
            'name'       => $data['name'],
            'code'       => $data['code'] ?? null,
            'status'     => (string) ((int) (bool) $data['status']), // normalize to '1' / '0'
            'created_by' => auth()->id() ?? 1, // adjust if you track user
        ]);

        return redirect()
            ->route('products.categories.index')
            ->with('success', 'Category created successfully.');
    }

    /**
     * GET /products/categories/{category}/edit
     * Route name: products.categories.edit
     */
    public function edit(Category $category)
    {
        return view('products.categories.edit', compact('category'));
    }

    /**
     * PUT/PATCH /products/categories/{category}
     * Route name: products.categories.update
     */
    public function update(Request $request, Category $category)
    {
        $data = $request->validate([
            'name'   => [
                'required', 'string', 'max:191',
                Rule::unique('rm_categories', 'name')->ignore($category->id),
            ],
            'code'   => ['nullable', 'string', 'max:191'],
            'status' => ['required', Rule::in(['0','1',0,1,true,false])],
        ]);

        $category->update([
            'name'       => $data['name'],
            'code'       => $data['code'] ?? null,
            'status'     => (string) ((int) (bool) $data['status']),
            'updated_by' => auth()->id() ?? null,
        ]);

        return redirect()
            ->route('products.categories.index')
            ->with('success', 'Category updated successfully.');
    }

    /**
     * DELETE /products/categories/{category}
     * Route name: products.categories.destroy
     */
    public function destroy(Category $category)
    {
        $category->delete();

        return redirect()
            ->route('products.categories.index')
            ->with('success', 'Category deleted successfully.');
    }
}
