<?php

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

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Http\Requests\SuperAdmin\StoreKabupatenRequest;
use App\Modules\Pilkades\Models\Kabupaten;
use App\Modules\Pilkades\Services\SlugGeneratorService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

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

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

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

    public function create(): View
    {
        return view('pilkades::super-admin.kabupaten.create');
    }

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

        if ($request->hasFile('logo')) {
            $data['logo'] = $request->file('logo')->store('kabupaten-logo', 'public');
        }

        Kabupaten::create($data);

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

    public function edit(Kabupaten $kabupaten): View
    {
        return view('pilkades::super-admin.kabupaten.edit', compact('kabupaten'));
    }

    public function update(StoreKabupatenRequest $request, Kabupaten $kabupaten): RedirectResponse
    {
        $data = $request->validated();

        if ($data['nama'] !== $kabupaten->nama) {
            $data['slug'] = $this->slugGenerator->generate(Kabupaten::class, $data['nama']);
        }

        if ($request->hasFile('logo')) {
            if ($kabupaten->logo) {
                Storage::disk('public')->delete($kabupaten->logo);
            }
            $data['logo'] = $request->file('logo')->store('kabupaten-logo', 'public');
        }

        $kabupaten->update($data);

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

    public function destroy(Kabupaten $kabupaten): RedirectResponse
    {
        $kabupaten->delete();

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