<?php

namespace App\Http\Controllers\Admin;

use App\Models\PestCategory;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Str;

class PestCategoryController extends Controller
{
    public function index()
    {
        $categories = PestCategory::with('image')->latest()->paginate(10);
        return view('admin.pest-categories.index', compact('categories'));
    }

    public function create()
    {
        return view('admin.pest-categories.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|unique:pest_categories,slug',
            'icon' => 'nullable|string|max:255',
            'image_id' => 'nullable|exists:images,id',
            'description' => 'nullable|string',
        ]);

        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }

        PestCategory::create($data);

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

    public function edit(PestCategory $pestCategory)
    {
        return view('admin.pest-categories.edit', compact('pestCategory'));
    }

    public function update(Request $request, PestCategory $pestCategory)
    {
        $data = $request->validate([
            'name' => 'required|string|max:255',
            'slug' => 'nullable|string|unique:pest_categories,slug,' . $pestCategory->id,
            'icon' => 'nullable|string|max:255',
            'image_id' => 'nullable|exists:images,id',
            'description' => 'nullable|string',
        ]);

        if (empty($data['slug'])) {
            $data['slug'] = Str::slug($data['name']);
        }

        $pestCategory->update($data);

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

    public function destroy(PestCategory $pestCategory)
    {
        $pestCategory->delete();
        return back()->with('success', 'Pest Category deleted successfully');
    }
}
