<?php

namespace App\Http\Controllers;

use App\Models\GaleriModel;
use Illuminate\Http\Request;

class GaleriController extends Controller
{
    public function index()
    {
        $data = GaleriModel::allGaleri();
        return view('dashboard.galeri.galeri', ['data' => $data]);
    }

    public function store(Request $request)
    {
        $imageName = time() . '.' . $request->foto->extension();

        $request->foto->move(public_path('storage/galeri'), $imageName);

        $galeri = new GaleriModel();
        $galeri->gambar = $imageName;
        $galeri->tanggal_post = date('Y-m-d');
        $galeri->save();

        return redirect()->route('galeri')
            ->with('success', 'Galeri berhasil ditambahkan');
    }

    public function update(Request $request, $id_galeri)
    {
        $galeri = GaleriModel::find($id_galeri);

        if ($request->hasFile('foto')) {
            if ($galeri->gambar && file_exists(public_path('storage/galeri/' . $galeri->gambar))) {
                unlink(public_path('storage/galeri/' . $galeri->gambar));
            }

            $imageName = time() . '.' . $request->foto->extension();
            $request->foto->move(public_path('storage/galeri'), $imageName);
            $galeri->gambar = $imageName;
        }

        $galeri->tanggal_post = date('Y-m-d');
        $galeri->save();

        return redirect()->route('galeri')
            ->with('success', 'Galeri berhasil diperbarui');
    }
    public function destroy(Request $request)
    {
        $id_galeri = $request->input('id_galeri');
        $galeri = GaleriModel::find($id_galeri);
        if ($galeri->gambar) {
            unlink(public_path('storage/galeri/' . $galeri->gambar));
        }
        $galeri->delete();
        return redirect()->route('galeri')
            ->with('success', 'Galeri berhasil dihapus');
    }
}
