<?php

function writeFile($filePath, $content) {
    try {
        $file = fopen($filePath, "w");
        if ($file === false) {
            throw new Exception("Error opening file: " . $filePath);
        }
        if (fwrite($file, $content) === false) {
            throw new Exception("Error writing to file: " . $filePath);
        }
        fclose($file);
    } catch (Exception $e) {
        error_log($e->getMessage());
        echo "Error Write Files";
    }
}


function resizeImage($imageString, $maxWidth, $maxHeight) {
	
	$formate = detectImageFormat($imageString);
	
	if($formate === 'Base64 Image'){
		
		// Remove the data URL part (optional, if present)
		$image_data = explode(',', $imageString);
		if (count($image_data) > 1) {
			$image_data = $image_data[1];
		} else {
			$image_data = $image_data[0];
		}

		// Decode the base64 data
		$image_data = base64_decode($image_data);
		
		// Create an image from the string
		$image = imagecreatefromstring($image_data);
		if ($image === false) {
			throw new Exception("Error creating image from string");
		}

		
	}else{
		
		//echo $formate ; die();
		
		// Create an image from the string
		$image = imagecreatefromstring($imageString);
		if ($image === false) {
			throw new Exception("Error creating image from string");
		}
		
	}
	


    $width = imagesx($image);
    $height = imagesy($image);

    $newWidth = $width;
    $newHeight = $height;

    // Calculate the new dimensions preserving aspect ratio
    if ($width > $maxWidth || $height > $maxHeight) {
        $aspectRatio = $width / $height;
        if ($width / $maxWidth > $height / $maxHeight) {
            $newWidth = $maxWidth;
            $newHeight = $maxWidth / $aspectRatio;
        } else {
            $newHeight = $maxHeight;
            $newWidth = $maxHeight * $aspectRatio;
        }
    }

    $newWidth = round($newWidth);
    $newHeight = round($newHeight);

    $newImage = imagecreatetruecolor($newWidth, $newHeight);
    imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
    imagedestroy($image);

    return $newImage;
}


function detectImageFormat($imageString) {
    // Check if the string starts with a base64 data URI scheme
    if (preg_match('/^data:image\/(\w+);base64,/', $imageString, $type)) {
        return 'Base64 Image';
    }

    // Check if the string contains only hexadecimal characters
    if (ctype_xdigit($imageString)) {
        return 'Hexadecimal String';
    }

    // Convert string to binary for exif_imagetype() checking if possible
    $binaryData = $imageString;

    // Check if it is a valid base64 and then decode to binary
    if ($decodedData = base64_decode($imageString, true)) {
        $binaryData = $decodedData;
    }

    // Write the binary data to a temporary file for format checking
    $tmpFile = tempnam(sys_get_temp_dir(), 'img');
    file_put_contents($tmpFile, $binaryData);

    // Use exif_imagetype() to determine the image type
    $imageType = exif_imagetype($tmpFile);
    unlink($tmpFile); // Clean up the temporary file

    if ($imageType !== false) {
        switch ($imageType) {
            case IMAGETYPE_GIF:
                return 'GIF Image';
            case IMAGETYPE_JPEG:
			case IMAGETYPE_JPEG2000: 
                return 'JPEG Image';
            case IMAGETYPE_PNG:
                return 'PNG Image';
            case IMAGETYPE_BMP:
                return 'BMP Image';
            case IMAGETYPE_WEBP:
                return 'WEBP Image';
            default:
                return 'Unknown Image Format';
        }
    }

    // If no match, return unknown
    return 'Unknown Format';
}



function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }
    
    if (!is_dir($dir)) {
        return unlink($dir);
    }
    
    $items = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($items as $item) {
        if ($item->isDir()) {
            rmdir($item->getRealPath());
        } else {
            unlink($item->getRealPath());
        }
    }
    
    return rmdir($dir);
}

?>