<?php

namespace App\Http\Controllers;

use App\Models\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class ImageController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $images = Image::all();
        return view('images.index', compact('images'));
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'image' => 'required|file',
        ]);
        if ($request->hasFile('image')) {
            $file = $request->file('image');
            $fileName = time() . '_' . Str::random(10) . '.' . $file->getClientOriginalExtension();
            $file->move(public_path('/image-storage'), $fileName);
        }

        Image::create([
            'name' => $fileName,
        ]);
        return redirect()->route('images.index')->with('success', 'Image uploaded successfully.');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $image = Image::findOrFail($id);

        $filePath = public_path('/image-storage/' . $image->name);
        if (file_exists($filePath)) {
            unlink($filePath);
        }

        $image->delete();
        return redirect()->route('images.index')->with('success', 'Image deleted successfully.');

    }
}
