<?php

namespace App\Http\Controllers\Admin;

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

class PestController extends Controller
{
    public function index()
    {
        $pests = Pest::with('category', 'image')->latest()->paginate(10);
        return view('admin.pests.index', compact('pests'));
    }

    public function create()
    {
        $categories = PestCategory::all();
        return view('admin.pests.create', compact('categories'));
    }

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

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

        Pest::create($data);

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

    public function edit(Pest $pest)
    {
        $categories = PestCategory::all();
        return view('admin.pests.edit', compact('pest', 'categories'));
    }

    public function update(Request $request, Pest $pest)
    {
        $data = $request->validate([
            'pest_category_id' => 'required|exists:pest_categories,id',
            'title' => 'required|string|max:255',
            'slug' => 'nullable|string|unique:pests,slug,' . $pest->id,
            'image_id' => 'nullable|exists:images,id',
            'description' => 'nullable|string',
        ]);

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

        $pest->update($data);

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

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