<?php

namespace App\Http\Controllers;

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

class CategoryController extends Controller
{
    public function index()
    {
        $categories = Category::withCount('inventoryItems')->latest()->get();

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

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120', 'unique:categories,nama_kategori'],
            'code' => ['required', 'string', 'max:20', 'unique:categories,kode_kategori'],
            'description' => ['nullable', 'string', 'max:500'],
        ]);

        Category::create([
            'nama_kategori' => $data['name'],
            'kode_kategori' => strtoupper($data['code']),
            'deskripsi' => $data['description'] ?? null,
        ]);

        return redirect()->route('categories.index')->with('success', 'Kategori berhasil ditambahkan.');
    }

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

    public function update(Request $request, Category $category)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120', Rule::unique('categories', 'nama_kategori')->ignore($category)],
            'code' => ['required', 'string', 'max:20', Rule::unique('categories', 'kode_kategori')->ignore($category)],
            'description' => ['nullable', 'string', 'max:500'],
        ]);

        $category->update([
            'nama_kategori' => $data['name'],
            'kode_kategori' => strtoupper($data['code']),
            'deskripsi' => $data['description'] ?? null,
        ]);

        return redirect()->route('categories.index')->with('success', 'Kategori berhasil diperbarui.');
    }

    public function destroy(Category $category)
    {
        if ($category->inventoryItems()->exists()) {
            return back()->with('error', 'Kategori masih digunakan oleh data barang.');
        }

        $category->delete();

        return redirect()->route('categories.index')->with('success', 'Kategori berhasil dihapus.');
    }
}
