<?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) {
    // Check if the directory exists
    if (!file_exists($dir)) {
        error_log("Directory does not exist: " . $dir);
        return true; // Directory is already deleted or doesn't exist
    }

    // If it's a file, try to delete it
    if (!is_dir($dir)) {
        if (unlink($dir)) {
            error_log("File deleted successfully: " . $dir);
            return true;
        } else {
            error_log("Error deleting file: " . $dir);
            return false;
        }
    }

    // Iterate through the directory and its contents
    $items = new RecursiveIteratorIterator(
        new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
        RecursiveIteratorIterator::CHILD_FIRST
    );

    foreach ($items as $item) {
        // If it's a directory, try to remove it
        if ($item->isDir()) {
            if (rmdir($item->getRealPath())) {
                error_log("Directory deleted: " . $item->getRealPath());
            } else {
                error_log("Error deleting directory: " . $item->getRealPath());
                return false; // Return false if there's an error
            }
        } else {
            // If it's a file, try to delete it
            if (unlink($item->getRealPath())) {
                error_log("File deleted: " . $item->getRealPath());
            } else {
                error_log("Error deleting file: " . $item->getRealPath());
                return false; // Return false if there's an error
            }
        }
    }

    // Try to remove the parent directory after all contents are deleted
    if (rmdir($dir)) {
        error_log("Parent directory deleted: " . $dir);
        return true;
    } else {
        error_log("Error deleting parent directory: " . $dir);
        return false; // Return false if there's an error
    }
}

function resizeImageImagick($imageData, $outputPath, $width = 200, $height = 200) {
    try {
		$imagick = new Imagick();
		$imagick->readImageBlob($imageData);
		$imagick->setImageFormat('jpeg');
		$imagick->resizeImage($width, $height, Imagick::FILTER_LANCZOS, 1, true);
		$imagick->writeImage($outputPath);
		$imagick->clear();
		$imagick->destroy();
	} catch (ImagickException $e) {
		error_log("Imagick Error: " . $e->getMessage());
		//resizeImageGD($imageData, $outputPath); // Fallback to GD if Imagick fails
	}
}


// function resizeImageGD($imageData, $outputPath, $width = 200, $height = 200) {
    // $sourceImage = imagecreatefromstring($imageData);
    // if ($sourceImage === false) {
        // throw new Exception('Failed to create image from string.');
    // }

    // $origWidth = imagesx($sourceImage);
    // $origHeight = imagesy($sourceImage);

    // $aspectRatio = $origWidth / $origHeight;
    // if ($width / $height > $aspectRatio) {
        // $width = $height * $aspectRatio;
    // } else {
        // $height = $width / $aspectRatio;
    // }

    // $thumbnailImage = imagecreatetruecolor($width, $height);
    // imagecopyresampled($thumbnailImage, $sourceImage, 0, 0, 0, 0, $width, $height, $origWidth, $origHeight);

    // $result = imagejpeg($thumbnailImage, $outputPath, 90);

    // imagedestroy($sourceImage);
    // imagedestroy($thumbnailImage);

    // if ($result === false) {
        // throw new Exception('Failed to write the resized image.');
//     }
// }



?>