<?php

namespace App\Http\Controllers\Admin;

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

class AboutContentController extends Controller
{
    public function edit()
    {
        // Fetch all about settings
        $settings = SiteSetting::where('key', 'like', 'about_%')->pluck('value', 'key')->toArray();
        return view('admin.about.edit', compact('settings'));
    }

    public function update(Request $request)
    {
        $data = $request->except('_token', '_method', 'about_image');
        
        if ($request->hasFile('about_image')) {
            $imageName = time() . '.' . $request->about_image->extension();
            $request->about_image->move(public_path('uploads/about'), $imageName);
            
            // Delete old image if exists
            $oldImage = SiteSetting::where('key', 'about_image')->first();
            if ($oldImage && $oldImage->value) {
                if (file_exists(public_path($oldImage->value))) {
                    @unlink(public_path($oldImage->value));
                }
            }
            
            SiteSetting::updateOrCreate(
                ['key' => 'about_image'],
                ['value' => 'uploads/about/' . $imageName]
            );
        }

        foreach ($data as $key => $value) {
            SiteSetting::updateOrCreate(
                ['key' => $key],
                ['value' => $value]
            );
        }

        return redirect()->back()->with('success', 'About Page content updated successfully');
    }
}
