<?php

namespace App\Http\Controllers;

use App\Models\About;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;

class AboutController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(About $about)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit( $id)
    {
         $about = About::findOrFail($id);
        return view('backend.pages.about.edit', compact('about'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request,  $id)
    {
        $about = About::findOrFail($id);

        $request->validate([
            'image'       => 'nullable|image',
            'title'        => 'nullable|string',
            'alt_text' => 'nullable|string',
            'description'  => 'nullable|string',
            'author' => 'nullable|string',
            'amazon_link' => 'nullable|string',

        ]);



        $imagePath = $about->image;

        if ($request->hasFile('image')) {
            // Delete old image safely
            if ($about->image && file_exists(public_path($about->image))) {
                @unlink(public_path($about->image));
            }

            $file = $request->file('image');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('storage/about_images'), $filename);
            $imagePath = 'storage/about_images/' . $filename;
        }

        $about->update([
            'image'       => $imagePath,
            'title'        => $request->title,
            'alt_text' => $request->alt_text,
            'amazon_link' => $request->amazon_link,
            'author' => $request->author,
            'description' => $request->description,


        ]);

            Alert::success('Success ', 'About item updated successfully.');
            return redirect()->route('about.edit', $about->id);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(About $about)
    {
        //
    }
}
