<?php

namespace App\Http\Controllers;

use App\Models\MaterialCategory;
use Illuminate\Http\Request;

class MaterialCategoryController extends Controller
{
    public function __construct()
    {
        $this->middleware(\App\Http\Middleware\PermissionMiddleware::class . ':manage materials,manage stock')
            ->only(['create', 'store', 'edit', 'update', 'destroy']);
    }
    public function index()
    {
        $categories = MaterialCategory::withCount('materials')
            ->orderBy('name')
            ->paginate(20);

        return view('pages.stock.categories.index', [
            'title' => 'Kategori Bahan',
            'categories' => $categories,
        ]);
    }

    public function create()
    {
        return view('pages.stock.categories.create', [
            'title' => 'Tambah Kategori',
        ]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:material_categories'],
            'description' => ['nullable', 'string', 'max:500'],
        ]);

        MaterialCategory::create($validated);

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

    public function edit(MaterialCategory $category)
    {
        return view('pages.stock.categories.edit', [
            'title' => 'Edit Kategori',
            'category' => $category,
        ]);
    }

    public function update(Request $request, MaterialCategory $category)
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255', 'unique:material_categories,name,' . $category->id],
            'description' => ['nullable', 'string', 'max:500'],
            'is_active' => ['boolean'],
        ]);

        $category->update([
            'name' => $validated['name'],
            'description' => $validated['description'] ?? null,
            'is_active' => $request->boolean('is_active'),
        ]);

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

    public function destroy(MaterialCategory $category)
    {
        if ($category->materials()->count() > 0) {
            return redirect()->route('stock.categories.index')
                ->with('error', 'Kategori tidak bisa dihapus karena masih memiliki bahan.');
        }

        $category->delete();

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