<?php

namespace App\Modules\Pilkades\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Http\Requests\SuperAdmin\StoreKecamatanRequest;
use App\Modules\Pilkades\Models\Kabupaten;
use App\Modules\Pilkades\Models\Kecamatan;
use App\Modules\Pilkades\Services\SlugGeneratorService;
use Illuminate\Http\RedirectResponse;
use Illuminate\View\View;

class KecamatanController extends Controller
{
    public function __construct(protected SlugGeneratorService $slugGenerator) {}

    public function index(): View
    {
        $kecamatan = Kecamatan::with('kabupaten')->withCount('desa')->latest()->paginate(15);

        return view('pilkades::super-admin.kecamatan.index', compact('kecamatan'));
    }

    public function create(): View
    {
        $kabupatenList = Kabupaten::orderBy('nama')->get();

        return view('pilkades::super-admin.kecamatan.create', compact('kabupatenList'));
    }

    public function store(StoreKecamatanRequest $request): RedirectResponse
    {
        $data = $request->validated();
        $data['slug'] = $this->slugGenerator->generate(
            Kecamatan::class,
            $data['nama'],
            'kabupaten_id',
            $data['kabupaten_id'],
        );

        Kecamatan::create($data);

        return redirect()->route('super-admin.kecamatan.index')
            ->with('success', 'Kecamatan berhasil ditambahkan.');
    }

    public function edit(Kecamatan $kecamatan): View
    {
        $kabupatenList = Kabupaten::orderBy('nama')->get();

        return view('pilkades::super-admin.kecamatan.edit', compact('kecamatan', 'kabupatenList'));
    }

    public function update(StoreKecamatanRequest $request, Kecamatan $kecamatan): RedirectResponse
    {
        $data = $request->validated();

        if ($data['nama'] !== $kecamatan->nama || $data['kabupaten_id'] !== $kecamatan->kabupaten_id) {
            $data['slug'] = $this->slugGenerator->generate(
                Kecamatan::class,
                $data['nama'],
                'kabupaten_id',
                $data['kabupaten_id'],
            );
        }

        $kecamatan->update($data);

        return redirect()->route('super-admin.kecamatan.index')
            ->with('success', 'Kecamatan berhasil diperbarui.');
    }

    public function destroy(Kecamatan $kecamatan): RedirectResponse
    {
        $kecamatan->delete();

        return redirect()->route('super-admin.kecamatan.index')
            ->with('success', 'Kecamatan berhasil dihapus.');
    }
}
