<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Potential;
use App\Services\ImageUploadService;
use Illuminate\Http\Request;

class PotentialController extends Controller
{
    public function __construct(private ImageUploadService $imageService) {}

    public function index()
    {
        $potentials = Potential::latest()->paginate(15);
        return view('admin.potentials.index', compact('potentials'));
    }

    public function create()
    {
        return view('admin.potentials.form', ['potential' => new Potential()]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'kategori'  => 'required|in:pertanian,perkebunan,umkm,pariwisata,peternakan',
            'nama'      => 'required|string|max:255',
            'deskripsi' => 'required|string',
            'lokasi'    => 'nullable|string|max:255',
            'foto'      => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
        ]);

        if ($request->hasFile('foto')) {
            $validated['foto'] = $this->imageService->upload($request->file('foto'), 'potentials');
        }

        Potential::create($validated);
        return redirect()->route('admin.potensi.index')->with('success', 'Potensi desa berhasil ditambahkan.');
    }

    public function edit(Potential $potensi)
    {
        return view('admin.potentials.form', ['potential' => $potensi]);
    }

    public function update(Request $request, Potential $potensi)
    {
        $validated = $request->validate([
            'kategori'  => 'required|in:pertanian,perkebunan,umkm,pariwisata,peternakan',
            'nama'      => 'required|string|max:255',
            'deskripsi' => 'required|string',
            'lokasi'    => 'nullable|string|max:255',
            'foto'      => 'nullable|image|mimes:jpg,jpeg,png,webp|max:2048',
        ]);

        if ($request->hasFile('foto')) {
            $validated['foto'] = $this->imageService->upload($request->file('foto'), 'potentials', $potensi->foto);
        }

        $potensi->update($validated);
        return redirect()->route('admin.potensi.index')->with('success', 'Potensi desa berhasil diperbarui.');
    }

    public function destroy(Potential $potensi)
    {
        $this->imageService->delete($potensi->foto);
        $potensi->delete();
        return redirect()->route('admin.potensi.index')->with('success', 'Potensi desa berhasil dihapus.');
    }
}
