<?php

namespace App\Modules\Pilkades\Http\Controllers\AdminDesa;

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Models\Banner;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class BannerController extends Controller
{
    public function index(): View
    {
        $banners = Banner::where('desa_id', Auth::user()->desa_id)->orderBy('urutan')->get();

        return view('pilkades::admin-desa.banner.index', compact('banners'));
    }

    public function store(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'judul' => ['required', 'string', 'max:255'],
            'gambar' => ['required', 'image', 'max:2048'],
            'urutan' => ['nullable', 'integer'],
        ]);

        $data['gambar'] = $request->file('gambar')->store('banners', 'public');
        $data['desa_id'] = Auth::user()->desa_id;

        Banner::create($data);

        return back()->with('success', 'Banner berhasil ditambahkan.');
    }

    public function destroy(Banner $banner): RedirectResponse
    {
        abort_unless($banner->desa_id === Auth::user()->desa_id, 403);

        Storage::disk('public')->delete($banner->gambar);
        $banner->delete();

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