<?php

//$url1="https://cars.zadio.bg/zadio/public/uploads/cars_img/CAR96A64Q3O1/11715782553574324_sj.jpg";
//echo resizeImg(urlencode($url1),400);

function resizeImg($url,$width)
{
    $IMGPATH='/home/zadio/cars.zadio.bg/zadio/public/uploads/cars_img';  
   
	$url = urldecode($url); // Decode the URL-encoded image path
    $urlEnc=normalizeUrl($url);
	//var_dump($urlEnc);exit;
	$e = explode("/",$url);
	$filename = $e[count($e)-1];
	
	$dirUrl = str_replace($filename,'',$url);
	
	//var_dump($filename);echo "<br>";
	$mainfolder=str_replace('/'.$filename,'',str_replace('https://cars.zadio.bg/uploads/cars_img/','',$url));
	//var_dump($mainfolder);echo "<br>";
	$dir= $IMGPATH.'/'.$mainfolder.'/cache';
	$newWidth = intval($width); // Ensure the width is an integer
	
	$newFilename=str_replace('.','_'.$newWidth.'px.', $filename);
	
    $savePath=$dir.'/'.$newFilename;
	$filePath=$dirUrl.'cache/'.$newFilename;
	//var_dump($dir);
	if (file_exists($savePath)) 
	{
		return  $filePath;     
	} 
	
	//var_dump($dir);exit;
	//MKdir if not exists
	if (!file_exists( $dir )) 
	{
		mkdir( $dir );       
	} 
	// Fetch the original image
    $imageInfo = @getimagesize($urlEnc);
    if ($imageInfo === false) {
       return null;
    }

    // Get original image dimensions
    list($originalWidth, $originalHeight) = $imageInfo;

    // Calculate the new height to maintain aspect ratio
    $newHeight = intval(($newWidth / $originalWidth) * $originalHeight);

    // Create a new blank image with the new dimensions
    $resizedImage = imagecreatetruecolor($newWidth, $newHeight);

    // Load the original image based on its mime type
	var_dump($imageInfo['mime']);
    switch ($imageInfo['mime']) {
        case 'image/jpeg':
            $sourceImage = imagecreatefromjpeg($urlEnc);
            break;
        case 'image/png':
            $sourceImage = imagecreatefrompng($urlEnc);
            break;
        case 'image/gif':
            $sourceImage = imagecreatefromgif($urlEnc);
            break;
		case 'image/webp':
            $sourceImage = imagecreatefromwebp($urlEnc);
            break;
        default:
            return null;
    }
	// Resize the image
    imagecopyresampled($resizedImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $originalWidth, $originalHeight);

    // save the resized image based on its mime type
    switch ($imageInfo['mime']) {
        case 'image/jpeg':
            imagejpeg($resizedImage,$savePath);
            break;
        case 'image/png':
            imagepng($resizedImage,$savePath);
            break;
        case 'image/gif':
            imagegif($resizedImage,$savePath);
            break;
		case 'image/webp':
			imagegif($resizedImage,$savePath);
            break;
    }

    // Free up memory
    imagedestroy($resizedImage);
    imagedestroy($sourceImage);
	
	return  $filePath;
} 

function normalizeUrl(string $url) {
	$parts = parse_url($url);
	return $parts['scheme'] .
		'://' .
		$parts['host'] .
		implode('/', array_map('rawurlencode', explode('/', $parts['path'])));

}