<?php

namespace App\Http\Controllers;

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


class CategoriesController extends Controller
{
     public function category()
    {
        // Get all categories ordered by newest first
        $categories = Category::withCount('products') // Count products in each category
            ->latest()
            ->get();

        return view('category', compact('categories'));
    }

    /**
     * Store a newly created category
     */
    public function store(Request $request)
    {
        // Validate the incoming data
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:categories,name',
        ]);

        // Auto-generate slug from name
        $validated['slug'] = Str::slug($validated['name']);

        // Create the category
        Category::create($validated);

        // Redirect back with success message
        return redirect()
            ->route('admin.categories.index')
            ->with('success', 'Category created successfully!');
    }

    /**
     * Show edit form for a specific category
     */
    public function edit(Category $category)
    {
        // Get all categories for the table
        $categories = Category::withCount('products')->latest()->get();

        // Return same view but with category to edit
        return view('category', compact('categories', 'category'));
    }

    /**
     * Update the specified category
     */
    public function update(Request $request, Category $category)
    {
        // Validate - exclude current category from unique check
        $validated = $request->validate([
            'name' => 'required|string|max:255|unique:categories,name,' . $category->id,
        ]);

        // Auto-generate slug from name
        $validated['slug'] = Str::slug($validated['name']);

        // Update the category
        $category->update($validated);

        // Redirect back with success message
        return redirect()
            ->route('admin.categories.index')
            ->with('success', 'Category updated successfully!');
    }

    /**
     * Delete the specified category
     */
    public function destroy(Category $category)
    {
        // Check if category has products
        $productCount = $category->products()->count();

        if ($productCount > 0) {
            return redirect()
                ->route('admin.categories.index')
                ->with('error', "Cannot delete category! It has {$productCount} product(s). Please delete or move the products first.");
        }

        // Delete the category
        $category->delete();

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