<?php

namespace App\Http\Controllers;

use App\Models\Image;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class ImageController extends Controller
{

    public function upload(Request $request)
    {
        $request->validate([
            'image' => 'required|image|max:2048',
        ]);

        $file = $request->file('image');
        $folder = 'blog/images';
        $filePath = $folder . '/' . time() . '_' . $file->getClientOriginalName();
        $uploaded = Storage::disk('s3')->put($filePath, file_get_contents($file), 'public');

        if (!$uploaded) {
            return response()->error('Failed to upload image to S3');
        }

        $url = Storage::disk('s3')->url($filePath);

        $image = Image::create([
            'file_name' => $file->getClientOriginalName(),
            'file_path' => $filePath,
            'mime_type' => $file->getMimeType(),
            'file_size' => $file->getSize(),
        ]);

        return response()->success('Image uploaded successfully', [
            'id' => $image->id,
            'file_name' => $image->file_name,
            'url' => $url,
        ]);
    }



    public function index()
    {
        $images = Image::all();
        return response()->success('Images retrieved successfully', $images);
    }

    /**
     * Получение изображения.
     */
    public function show($id)
    {
        $image = Image::findOrFail($id);

        if (!Storage::disk('s3')->exists($image->file_path)) {
            return response()->errorNotFound('Image not found');
        }
        $url = Storage::disk('s3')->url($image->file_path);

        return response()->success('Image URL retrieved successfully', [
            'id' => $image->id,
            'file_name' => $image->file_name,
            'url' => $url,
        ]);
    }


//    public function removeImage($id)
//    {
//        $image = Image::findOrFail($id);
//
//        if (!Storage::disk('public')->exists($image->file_path)) {
//            return response()->errorNotFound('Image not found');
//        }
//
//        Storage::disk('public')->delete($image->file_path);
//        $image->delete();
//
//        return response()->success('Image removed successfully');
//    }
}
