<?php

namespace App\Http\Controllers;

use App\Models\FeatureImage;
use Illuminate\Http\Request;

class FeatureImageController extends Controller
{
    // Fetch all feature images
    public function index()
    {
        $images =  FeatureImage::latest()->get()->take(1); // Get the latest inserted record


        return response()->json($images);
    }

    // Store a new feature image
    public function store(Request $request)
    {
        $request->validate([
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif,webp,WebP|max:2048',
        ]);

        $featureImage = new FeatureImage();

        if ($request->hasFile('image')) {
            // Manually move the file to the public/app-feature-images directory
            $image = $request->file('image');
            $fileName = time() . '_' . $image->getClientOriginalName();
            $destinationPath = public_path('/app-feature-images');
            $image->move($destinationPath, $fileName);

            // Construct the URL to the stored file
            $url = asset('app-feature-images/' . $fileName);

            $featureImage->url = $url;
        }

        $featureImage->save();

        return response()->json(['message' => 'Feature image uploaded successfully', 'image' => $featureImage], 201);
    }
    // Delete a feature image
    public function destroy($id)
    {
        $featureImage = FeatureImage::findOrFail($id);

        // Delete the image file from the public directory
        $imagePath = public_path('app-feature-images/' . $featureImage->url);

        if (file_exists($imagePath)) {
            unlink($imagePath);
        }

        // Delete the record from the database
        $featureImage->delete();

        return response()->json(['message' => 'Image deleted successfully']);
    }
}
