<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Galeri;
use Illuminate\Http\Request;

class GaleriController extends Controller
{
    public function index()
    {
        $imgFolder = public_path('img'); // folder gambar di public/img
        $files = scandir($imgFolder);

        foreach ($files as $file) {
            if (in_array($file, ['.', '..'])) continue;

            // otomatis insert ke database jika belum ada
            Galeri::firstOrCreate(
                ['gambar' => $file],
                [
                    'judul' => pathinfo($file, PATHINFO_FILENAME),
                    'foto'  => $file, // kolom foto diisi nama file
                ]
            );
        }

        $galeris = Galeri::all();
        return view('admin.galeri.index', compact('galeris'));
    }

    public function edit($id)
    {
        $galeri = Galeri::findOrFail($id);
        return view('admin.galeri.edit', compact('galeri'));
    }

    public function update(Request $request, $id)
{
    $galeri = Galeri::findOrFail($id);

    $request->validate([
        'judul' => 'required|string|max:255',
        'foto' => 'nullable|image|mimes:jpg,jpeg,png,gif|max:2048',
    ]);

    if ($request->hasFile('foto')) {
        // Simpan foto baru dengan nama file lama
        $file = $request->file('foto');
        $filename = $galeri->foto; // tetap pakai nama lama
        $file->move(public_path('img'), $filename);
    }

    $galeri->judul = $request->judul;
    $galeri->save();

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

}
