<?php

namespace App\Http\Controllers\Services;

use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UploadController extends Controller
{

    // Delete image from public path deleteImage('habijabi.jpg', 'uploads/products')
    public static function deleteImage($imageName, $path)
    {
        if (!empty($imageName) && file_exists($path . '/' . $imageName)) {
            unlink($path . '/' . $imageName);
            return true;
        }else{
            return false;
        }
    }

    // Delete image from public path deleteImageFromPublicPath('habijabi.jpg', 'uploads/products')
    public static function deleteImageFromPublicPath($imageName, $path)
    {
        if (!empty($imageName) && file_exists(public_path($path . '/' . $imageName))) {
            if($path){
                unlink(public_path($path . '/' . $imageName));
                return true;
            } else {
                unlink(public_path($imageName));
                return true;
            }
            return false;
        }
        return false;
    }

    // Upload image to public path
    public static function uploadImageToPublicPath($image, $path)
    {
        $validExtensions = ['jpg', 'jpeg', 'png', 'gif', 'svg', 'webp', 'JPEG', 'JPG', 'PNG', 'GIF', 'SVG', 'WEBP'];

        if ($image && in_array(Str::lower($image->getClientOriginalExtension()), $validExtensions)) {
            
            $imageName = time() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path($path), $imageName); // example: path() means public_path('uploads/products')
            return $path . '/' . $imageName;
        }
        
        return null;
    }


    // Upload multiple images to public path
    public static function uploadMultipleImagesToPublicPath($images, $path)
    {
        $imageNames = array_filter(array_map(function($image) use ($path) {
            // Generate a unique name for each image to prevent overwriting
            $imageName = time() . '_' . Str::random(10) . '.' . $image->getClientOriginalExtension();
            $image->move(public_path($path), $imageName);
            return $path . '/' . $imageName;
        }, $images));
        return $imageNames;
    }







}