<?php

namespace App\Http\Controllers\Api;

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

class PestApiController extends Controller
{
    public function categories()
    {
        $categories = PestCategory::with('image', 'pests', 'pests.image')->get();
        return response()->json([
            'status' => 'success',
            'data' => $categories
        ]);
    }

    public function pests(Request $request)
    {
        $query = Pest::with('category', 'image');

        if ($request->has('category_id')) {
            $query->where('pest_category_id', $request->category_id);
        }

        if ($request->has('category_slug')) {
            $query->whereHas('category', function($q) use ($request) {
                $q->where('slug', $request->category_slug);
            });
        }

        $pests = $query->latest()->get();

        return response()->json([
            'status' => 'success',
            'data' => $pests
        ]);
    }

    public function pestDetail($slug)
    {
        $pest = Pest::with('category', 'image')->where('slug', $slug)->first();

        if (!$pest) {
            return response()->json([
                'status' => 'error',
                'message' => 'Pest not found'
            ], 404);
        }

        return response()->json([
            'status' => 'success',
            'data' => $pest
        ]);
    }
}
