<?php

namespace App\Helper;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Intervention\Image\Facades\Image;

class ImageHelper
{
    // Define the different sizes to convert to
    public const sizes = ['small' => [100, 100], 'medium' => [500, 500], 'large' => [1000, 1000]];

    /**
     * Store a list of images
     *
     * @param array $images
     * @param string $directory
     * @return array
     */
    public static function storeImages(array $images, string $directory): array
    {
        $storedImagePaths = [];

        foreach ($images as $image) {
            // Validate image
            $validator = Validator::make(
                ['image' => $image],
                ['image' => 'required|image|max:100'] // max size 100
            );

            if ($validator->fails()) {
                // Handle validation failure
                continue;
            }

            $extension = $image->getClientOriginalExtension();

            // Store original image
            $iamgeName = 'original.' . $extension;
            $path = $image->storeAs("img/$directory",$iamgeName,'public');
            $storedImagePaths['original'] = Storage::url($path);

            foreach (ImageHelper::sizes as $size => [$width, $height]) {
                // Resize image
                $resizedImage = Image::make($image)->resize($width, $height, function ($constraint) {
                    $constraint->aspectRatio();
                    $constraint->upsize();
                });

                // Store resized image
                $resizedImagePath = "$directory/$size.$extension";
                Storage::disk('public')->put("img/$resizedImagePath", (string) $resizedImage->encode());
                $storedImagePaths[$size] = Storage::url("img/$resizedImagePath");
            }
        }

        return $storedImagePaths;
    }

    public static function getAllSizes($directory, $id): array
    {
        $paths = [];

        $files = Storage::disk('public')->allFiles('company/31');

        // Filter the list to include only files that start with "small"
        foreach (ImageHelper::sizes as $size => [$width, $height]) {
            $image = array_filter($files, function ($file) {
                return preg_match('/^size.+/', basename($file)) && ! is_dir($file);
            });

            $paths[$size] = Storage::url("img/$image");
        }

        return $paths;
    }
}
