<?php

namespace App\Http\Controllers\Services;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;

class ImageUploadController extends Controller
{
    public function index(Request $request)
    {
        // Validate the incoming request to ensure it contains a file
        $request->validate([
            'file' => 'required|file|mimes:jpeg,png,gif,bmp,tiff,webp,heic|max:20480', // Allow all image file types, maximum size of 2MB (you can adjust the size as needed)
        ]);

        // Get the file from the request
        $file = $request->file('file');

        // Generate a unique filename for the uploaded file and LQIP version
        $uuid = Str::uuid()->toString();
        $fileName = time().'_'.$uuid.'.jpg';
        $lqipFileName = time().'_'.$uuid.'_lqip.jpg';

        // Convert the file to JPEG format using Intervention Image library
        $image = Image::make($file->getRealPath())->encode('jpg', 100);

        // Get the original image width and height
        $originalWidth = $image->width();
        $originalHeight = $image->height();

        // Resize/upscale the image to 1920x1080 maintaining the aspect ratio and cropping if needed
        $image->fit(1920, 1080, function ($constraint) {
            $constraint->upsize();
            $constraint->aspectRatio();
        });

        // Compress the image to reduce file size to 50%
        $image->encode('jpg', 50);

        // Save the processed image to the 'r2' storage driver under the 'uploads' directory
        $filePath = 'uploads/'.$fileName;
        $lqipFilePath = 'uploads/'.$lqipFileName;
        Storage::disk('r2')->put($filePath, $image->stream()->detach());

        // Save the original image to a temporary file and open it again
        $tempImagePath = tempnam(sys_get_temp_dir(), 'temp_image');
        file_put_contents($tempImagePath, $file->get());
        $clonedImage = Image::make($tempImagePath);

        // Create the LQIP version of the image using a small size while maintaining the aspect ratio
        $lqipImage = $clonedImage->fit(10, 10, function ($constraint) {
            $constraint->aspectRatio();
        });
        $lqipImage->encode('jpg', 5);
        Storage::disk('r2')->put($lqipFilePath, $lqipImage->stream()->detach());

        // Cleanup the temporary image file
        unlink($tempImagePath);

        // Get the final URL of the uploaded image (non-LQIP version)
        $url = Storage::disk('r2')->url($filePath);

        // Return the JSON response with the image URL (non-LQIP version)
        return response()->json([
            'success' => 1,
            'file' => [
                'url' => $url,
            ],
        ]);
    }
}
