<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Buket;
use App\Http\Requests\Admin\BuketRequest; // Panggil Request baru kamu
use Illuminate\Support\Facades\Storage;

class BuketController extends Controller
{
    public function index()
    {
        $buket = Buket::latest()->get();
        return view('admin.produk-buket.index', compact('buket'));
    }

    public function store(BuketRequest $request)
    {
        $data = $request->validated();
        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $data['foto'] = $file->storeAs('img/buket', $filename, 'public');
        }
        Buket::create($data);
        return redirect()->back()->with('success', 'Produk buket berhasil ditambahkan!');
    }

    public function update(BuketRequest $request, string $id)
    {
        $buket = Buket::findOrFail($id);
        $data = $request->validated();
        if ($request->hasFile('foto')) {
            if ($buket->foto) {
                Storage::disk('public')->delete($buket->foto);
            }
            $file = $request->file('foto');
            $filename = time() . '_' . $file->getClientOriginalName();
            $data['foto'] = $file->storeAs('img/buket', $filename, 'public');
        }
        $buket->update($data);
        return redirect()->back()->with('success', 'Produk buket berhasil diperbarui!');
    }

    public function destroy(string $id)
    {
        $buket = Buket::findOrFail($id);
        if ($buket->foto) {
            Storage::disk('public')->delete($buket->foto);
        }
        $buket->delete();
        return redirect()->back()->with('success', 'Produk dan foto berhasil dihapus permanen!');
    }
}
