<?php

namespace App\Http\Controllers\Admin;

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

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

    public function index()
    {
        $galleries = Gallery::latest()->paginate(20);
        return view('admin.galleries.index', compact('galleries'));
    }

    public function create()
    {
        return view('admin.galleries.form', ['gallery' => new Gallery()]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'kategori' => 'required|in:kegiatan_desa,masyarakat,alam_lingkungan,potensi_desa,pemerintahan,wisata',
            'judul'    => 'nullable|string|max:255',
            'foto'     => 'required|array|min:1',
            'foto.*'   => 'image|mimes:jpg,jpeg,png,webp|max:2048',
        ]);

        foreach ($request->file('foto') as $file) {
            $path = $this->imageService->upload($file, 'galleries');
            Gallery::create([
                'kategori' => $request->kategori,
                'judul'    => $request->judul,
                'foto'     => $path,
            ]);
        }

        return redirect()->route('admin.galeri.index')->with('success', 'Foto galeri berhasil diunggah.');
    }

    public function edit(Gallery $galeri)
    {
        return view('admin.galleries.form', ['gallery' => $galeri]);
    }

    public function update(Request $request, Gallery $galeri)
    {
        $validated = $request->validate([
            'kategori' => 'required|in:kegiatan_desa,masyarakat,alam_lingkungan,potensi_desa,pemerintahan,wisata',
            'judul'    => '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'), 'galleries', $galeri->foto);
        }

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

    public function destroy(Gallery $galeri)
    {
        $this->imageService->delete($galeri->foto);
        $galeri->delete();
        return redirect()->route('admin.galeri.index')->with('success', 'Foto galeri berhasil dihapus.');
    }
}
