<?php

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

use App\Http\Controllers\Controller;
use App\Modules\Pilkades\Http\Requests\AdminDesa\UpdateProfilDesaRequest;
use App\Modules\Pilkades\Models\LandingPage;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\View\View;

class ProfilDesaController extends Controller
{
    public function edit(): View
    {
        $landingPage = LandingPage::firstOrCreate(['desa_id' => Auth::user()->desa_id]);

        return view('pilkades::admin-desa.profil.edit', compact('landingPage'));
    }

    public function update(UpdateProfilDesaRequest $request): RedirectResponse
    {
        $landingPage = LandingPage::firstOrCreate(['desa_id' => Auth::user()->desa_id]);
        $data = $request->validated();

        if ($request->hasFile('og_image')) {
            if ($landingPage->og_image) {
                Storage::disk('public')->delete($landingPage->og_image);
            }
            $data['og_image'] = $request->file('og_image')->store('landing-og', 'public');
        }

        $landingPage->update($data);

        return back()->with('success', 'Profil desa berhasil diperbarui.');
    }
}
