<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
use App\Models\CarouselImage;
use Illuminate\Support\Str;

class CarouselImageController extends Controller
{
    public function uploadCarouselPhoto(Request $request)
    {
        $request->validate([
            'photos.*' => 'required|image|mimes:jpeg,png,jpg|max:5120',
        ]);

        $folder = public_path('/images/carousel/');

        if (!file_exists($folder)) {
            mkdir($folder, 0777, true);
        }

        if ($request->hasFile('photos')) {
            foreach ($request->file('photos') as $file) {
                $fileName = Str::uuid() . '.' . $file->getClientOriginalExtension();
                $filePath = $folder . '/' . $fileName;

                // Resize image using Intervention before saving
                $image = Image::make($file->getRealPath());

                // Resize by height only, keep aspect ratio, do not upscale
                $image->resize(null, 800, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });

                $image->save($filePath, 90);

                CarouselImage::create([
                    'image_path' => $fileName,
                ]);
            }

            return response()->json(['status' => 1, 'message' => 'Images uploaded and resized successfully.']);
        }

        return response()->json(['status' => 0, 'message' => 'No files uploaded.']);
    }
    public function listCarouselPhoto()
    { {
            // Load the album with its photos

            $photos = CarouselImage::orderBy('id', 'desc')->get();
            $data = [
                'photos' => $photos,
                'pageTitle' => 'Manage Carousel Photo',
            ];

            return view('back.pages.carouselphoto.carousel_photo_list', $data);
        }
    }

    public function homepageImage() {}
}
