<?php

namespace App\Http\Controllers\Admin;

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

class LandingSettingController extends Controller
{
     public function index()
    {
        $settings = \App\Models\LandingSetting::all()->pluck('value', 'key');
        // Activities for the 3rd card
        $activities = \App\Models\RoutineActivity::all();
        
        return view('admin.settings.index', compact('settings', 'activities'));
    }

   public function update(Request $request)
{
    // Validasi dulu
    $request->validate([
        'about_image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
    ]);

    // Simpan semua input kecuali gambar
    foreach ($request->except(['_token', '_method', 'about_image']) as $key => $value) {
        LandingSetting::updateOrCreate(
            ['key' => $key],
            [
                'value' => $value,
                'type'  => 'text'
            ]
        );
    }

    // Jika ada upload gambar
  if ($request->hasFile('about_image')) {

    $old = LandingSetting::where('key', 'about_image')->first();

    // Hapus gambar lama jika ada
    if ($old && $old->value && file_exists(public_path($old->value))) {
        unlink(public_path($old->value));
    }

    $file = $request->file('about_image');
    $filename = time() . '.' . $file->getClientOriginalExtension();

    // Buat folder jika belum ada
    if (!file_exists(public_path('uploads/settings'))) {
        mkdir(public_path('uploads/settings'), 0755, true);
    }

    $file->move(public_path('uploads/settings'), $filename);

    LandingSetting::updateOrCreate(
        ['key' => 'about_image'],
        [
            'value' => 'uploads/settings/' . $filename,
            'type'  => 'image'
        ]
    );
}


    return back()->with('success', 'Pengaturan berhasil diperbarui!');
}

}
