<?php

namespace App\Http\Controllers;

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

class CategoryController extends Controller
{
    // =========================
    // LIST KATEGORI
    // =========================
    public function index()
    {
        $categories = Category::latest()->get();
        return view('categories.index', compact('categories'));
    }

    // =========================
    // FORM TAMBAH KATEGORI
    // =========================
    public function create()
    {
        return view('categories.create');
    }

    // =========================
    // SIMPAN KATEGORI BARU
    // =========================
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:categories,name',
        ]);

        Category::create([
            'name' => $request->name,
        ]);

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

    // =========================
    // FORM EDIT KATEGORI
    // =========================
    public function edit(Category $category)
    {
        return view('categories.edit', compact('category'));
    }

    // =========================
    // UPDATE KATEGORI
    // =========================
    public function update(Request $request, Category $category)
    {
        $request->validate([
            'name' => 'required|string|max:255|unique:categories,name,' . $category->id,
        ]);

        $category->update([
            'name' => $request->name,
        ]);

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

    // =========================
    // HAPUS KATEGORI
    // =========================
    public function destroy(Category $category)
    {
        if (method_exists($category, 'products') && $category->products()->exists()) {
            return back()->with(
                'error',
                'Kategori tidak bisa dihapus karena masih memiliki produk.'
            );
        }

        $category->delete();

        return back()->with('success', 'Kategori berhasil dihapus.');
    }
}
