<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Hero;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class HeroController extends Controller
{
    public function index()
    {
        $heroes = Hero::latest()->get();
        return view('admin.hero.index', compact('heroes'));
    }

    public function create()
    {
        return view('admin.hero.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'image' => 'required|image|mimes:jpg,jpeg,png|max:5120'
        ]);

        $image = $request->file('image')->store('hero', 'public');

        Hero::create([
            'judul' => $request->judul,
            'deskripsi' => $request->deskripsi,
            'image' => $image,
            'status' => $request->status ?? 1
        ]);

        return redirect()->route('hero.index')->with('success', 'Hero berhasil ditambahkan');
    }

    public function edit(Hero $hero)
    {
        return view('admin.hero.edit', compact('hero'));
    }

    public function update(Request $request, Hero $hero)
    {
        if ($request->hasFile('image')) {
            Storage::disk('public')->delete($hero->image);
            $hero->image = $request->file('image')->store('hero', 'public');
        }

        $hero->update([
            'judul' => $request->judul,
            'deskripsi' => $request->deskripsi,
            'status' => $request->status
        ]);

        return redirect()->route('hero.index')->with('success', 'Hero berhasil diupdate');
    }

    public function destroy(Hero $hero)
    {
        Storage::disk('public')->delete($hero->image);
        $hero->delete();

        return back()->with('success', 'Hero berhasil dihapus');
    }
}
