<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\AboutPage;

class AboutController extends Controller
{
    public function index()
    {
        $about = AboutPage::first(); // or where('id', 1)->first()
        return view('admin.about.index', compact('about'));
    }

    public function edit()
    {
        $about = AboutPage::first();
        return view('admin.about.edit', compact('about'));
    }

    public function update(Request $request)
    {
        $request->validate([
            'title' => 'required|string|max:255',
            'body' => 'required|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,webp',
        ]);

        // Fetch the first (and only) about page record, or create a new one
        $about = AboutPage::first();

        if (!$about) {
            $about = new AboutPage();
        }

        $about->title = $request->title;
        $about->body = $request->body;

        if ($request->hasFile('image')) {
            $image = $request->file('image');
            $imagePath = 'assets/admin/about-images/';
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path($imagePath), $imageName);
            $about->image = $imagePath . $imageName;
        }

        $about->save();

        return redirect()->route('admin.about.index')->with('success', 'About Us saved successfully.');
    }

}
