<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Kategori;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class KategoriController extends Controller
{
    public function index(Request $request): View
    {
        $kategoris = Kategori::query()
            ->withCount('wisatas')
            ->when($request->search, fn ($query, string $search) => $query->where('nama', 'like', "%{$search}%"))
            ->latest()
            ->paginate(10)
            ->withQueryString();

        return view('admin.kategori.index', compact('kategoris'));
    }

    public function create(): View
    {
        return view('admin.kategori.form', ['kategori' => new Kategori()]);
    }

    public function store(Request $request): RedirectResponse
    {
        $validated = $request->validate($this->rules());
        $validated['slug'] = Str::slug($validated['nama']);

        Kategori::query()->create($validated);

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

    public function edit(Kategori $kategori): View
    {
        return view('admin.kategori.form', compact('kategori'));
    }

    public function update(Request $request, Kategori $kategori): RedirectResponse
    {
        $validated = $request->validate($this->rules($kategori));
        $validated['slug'] = Str::slug($validated['nama']);

        $kategori->update($validated);

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

    public function destroy(Kategori $kategori): RedirectResponse
    {
        if ($kategori->wisatas()->exists()) {
            return back()->with('error', 'Kategori masih digunakan oleh data wisata.');
        }

        $kategori->delete();

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

    private function rules(?Kategori $kategori = null): array
    {
        return [
            'nama' => ['required', 'string', 'max:120', Rule::unique('kategoris', 'nama')->ignore($kategori)],
            'deskripsi' => ['nullable', 'string', 'max:1000'],
        ];
    }
}
