<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Additional;
use App\Models\PaketFoto;
use App\Http\Requests\Admin\FotoRequest; // Gunakan Request baru
use Illuminate\Support\Facades\Storage;

class FotoController extends Controller
{
    public function index()
    {
        $foto = PaketFoto::latest()->get();
        $additional = Additional::latest()->get();
        return view('admin.paket-foto.index', compact('foto', 'additional'));
    }

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

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

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