<?php

/**
 * Manage User Image Upload Files
 *
 * PHP version 5.6
 *
 * @category  User_Image
 * @package   Eloquent
 * @author    Satyabrata <satyabratap@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */

namespace App\Modules\Images\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Images\Models\BrowserImages;
use App\Modules\Images\Models\UserImage;
use App\Modules\Settings\Models\Setting;

/**
 * Upload Image Controller
 *
 * @category Class
 * @package  Upload_Image
 * @author   Mukesh <mukeshp@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */
class ImageController extends ParentController
{

	/**
	 * POST: Save Word Cloud
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author mukeshp@riaxe.com
	 * @date   7th Feb 2020
	 * @return json response wheather data is saved or any error occured
	 */
	public function saveUserImages($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Upload Image', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$customerId = $allPostPutVars['customer_id'];
		$ext = strtolower($allPostPutVars['file_type']);
		$storeId = $allPostPutVars['store_id'] ? $allPostPutVars['store_id'] : 1;
		$isS3Enabled = $this->checkS3Settings($storeId);
		$cloudStorage = 0;
		$source = $allPostPutVars['source'] ? $allPostPutVars['source'] : '';
		$originalFileUrl = '';
		if ($ext != 'jpg' && $ext != 'svg' && $ext != 'png' && $ext != 'jpeg') {
			$uploadUserFile = do_upload('userfile', path('abs', 'upload'), [], 'string');
			$originalFileUrl = path('read', 'upload') . $uploadUserFile;
			$new_file_name = (explode(".", $uploadUserFile));
			$outputFile = $new_file_name[0] . '.svg';
			$getUploadedFileName = $this->convertImageFormat($uploadUserFile, 'svg');
		} else {
			// thumb will not be generated
			$getUploadedFileName = do_upload('userfile', path('abs', 'user'), [], 'string');
			$originalFileUrl = path('read', 'user') . $getUploadedFileName;
			$outputFile = $getUploadedFileName;
		}
		if ($isS3Enabled) {
			$cloudStorage = 1;
			$fileToUpload = path('abs', 'user') . $getUploadedFileName;
			$s3Upload = $this->uploadFileToS3("user", $fileToUpload, $storeId);
			//$originalFileUrl = $s3Upload['S3URL'];
		}
		if (!empty($getUploadedFileName)) {
			$saveUserImageData = [
				'customer_id' => $customerId,
				'file_name' => $outputFile,
				'original_file_name' => $getUploadedFileName,
				'cloud_storage' => $cloudStorage,
			];
			$saveUserImage = new UserImage($saveUserImageData);
			if ($saveUserImage->save()) {
				$jsonResponse = [
					'status' => 1,
					'message' => message('User Image', 'saved'),
					'data' => [
						'file_name' => $getUploadedFileName,
						'original_file_url' => $originalFileUrl,
						'url' => $isS3Enabled == 1 ? $s3Upload['S3URL'] : path('read', 'user') . $getUploadedFileName,
					],
				];
			}
		}

		if ($storeId > 1 && empty($source) && IS_HOSTED == 0) {
			$storeResponse = $this->getStoreDomainName($storeId);
			if (!empty($storeResponse)) {
				$hostname = parse_url($jsonResponse['data']['url'], PHP_URL_HOST); //hostname
				$jsonResponse['data']['url'] = str_replace($hostname, $storeResponse['store_url'], $jsonResponse['data']['url']);
			}
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * GET: List of User Images
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author mukeshp@riaxe.com
	 * @date   7th Feb 2020
	 * @return All/Single User Images List
	 */
	public function getUserImages($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'data' => [],
			'message' => message('User Images', 'not_found'),
		];

		$UserImageInit = new UserImage();
		$getUserImages = $UserImageInit->where(
			'customer_id',
			'=',
			$args['id']
		);

		if ($getUserImages->count() > 0) {
			$userImages = $getUserImages->get()
				->toArray();
			$jsonResponse = [
				'status' => 1,
				'records' => count($userImages),
				'data' => $userImages,
			];
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * GET: Convert Image From One format to another
	 *
	 * @param $file_name   Slim's Request object
	 * @param $file_format Slim's Response object
	 *
	 * @author chandrakanta@riaxe.com
	 * @date   18th Mar 2020
	 * @return All/Single User Images List
	 */
	protected function convertImageFormat($file_name, $file_format)
	{
		$new_file_name = (explode(".", $file_name));
		$outputFile = $new_file_name[0] . '.svg';
		if ($new_file_name[1] == 'ai' || $new_file_name[1] == 'pdf' || $new_file_name[1] == 'cdr') {
			$versionDetails = shell_exec("inkscape -V");
			$version = explode(' ', $versionDetails);
			if ($version[1] >= 1) {
				$cmd = ($new_file_name[1] == 'ai') ? '--pdf-poppler ' : '';
				// latest version
				shell_exec("PATH=/usr/bin inkscape " . $cmd . "--export-filename=" . ASSETS_PATH_W . 'user/' . $outputFile . " " . ASSETS_PATH_W . 'user/uploads/' . $file_name);
			} else {
				// older version
				shell_exec("PATH=/usr/bin inkscape " . ASSETS_PATH_W . 'user/uploads/' . $file_name . "  --export-plain-svg=" . ASSETS_PATH_W . 'user/' . $outputFile);
			}
		} elseif ($new_file_name[1] == 'eps') {
			$outputFile = $new_file_name[0] . '.png';
			//shell_exec('convert ' . ASSETS_PATH_W . 'user/uploads/' . $file_name . " " . ASSETS_PATH_W . 'user/' . $outputFile );
			$sourcePath = ASSETS_PATH_W . 'user/uploads/' . $file_name;
			$destinationPath = ASSETS_PATH_W . 'user/' . $outputFile;
			$this->phpImageMagicTypeConvert($sourcePath, $destinationPath);
		} elseif ($new_file_name[1] == 'gif' || $new_file_name[1] == 'psd') {
			$outputFile = $new_file_name[0] . '.png';
			//shell_exec("convert " . ASSETS_PATH_W . 'user/uploads/' . $file_name . " " . $outputFile . " && mv " . $new_file_name[0] . "-0.png " . ASSETS_PATH_W . 'user/' . $outputFile . "  && rm -rf " . $new_file_name[0] . "-*.png");
			//shell_exec('convert ' . ASSETS_PATH_W . 'user/uploads/' . $file_name . " " . ASSETS_PATH_W . 'user/' . $outputFile );
			$sourcePath = ASSETS_PATH_W . 'user/uploads/' . $file_name;
			$destinationPath = ASSETS_PATH_W . 'user/' . $outputFile;
			$this->phpImageMagicTypeConvert($sourcePath, $destinationPath);
		} elseif ($new_file_name[1] == 'bmp' || $new_file_name[1] == 'tif') {
			$outputFile = $new_file_name[0] . '.png';
			//shell_exec("convert " . ASSETS_PATH_W . 'user/uploads/' . $file_name . " " . $outputFile . " && mv " . $outputFile . " " . ASSETS_PATH_W . 'user/' . $outputFile);
			$sourcePath = ASSETS_PATH_W . 'user/uploads/' . $file_name;
			$destinationPath = ASSETS_PATH_W . 'user/' . $outputFile;
			$this->phpImageMagicTypeConvert($sourcePath, $destinationPath);
		} else {
			//shell_exec("convert " . ASSETS_PATH_W . 'user/uploads/' . $file_name . " " . ASSETS_PATH_W . 'user/uploads/' . $new_file_name[0] . ".pnm && convert " . ASSETS_PATH_W . 'user/uploads/' . $new_file_name[0] . ".pnm " . ASSETS_PATH_W . 'user/' . $outputFile);
			$sourcePath = ASSETS_PATH_W . 'user/uploads/' . $file_name;
			$destinationPath = ASSETS_PATH_W . 'user/uploads/' . $new_file_name[0] . ".pnm";
			$this->phpImageMagicTypeConvert($sourcePath, $destinationPath);
			$newDestinationPath = ASSETS_PATH_W . 'user/' . $outputFile;
			$this->phpImageMagicTypeConvert($destinationPath, $newDestinationPath);
		}
		return $outputFile;
	}
	/**
	 * GET: Filter Image Whites
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author chandrakanta@riaxe.com
	 * @date   18th Mar 2020
	 * @return All/Single User Images List
	 */
	public function filterImage($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Upload Image', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$ext = $allPostPutVars['file_type'];
		$type = $allPostPutVars['type'];
		if ($ext == 'jpg' || $ext == 'png' || $ext == 'jpeg') {
			$getUploadedFileName = do_upload('userfile', path('abs', 'upload'), [], 'string');
			$new_file_name = (explode(".", $getUploadedFileName));
			$outputFile = $new_file_name[0] . '.png';
			// shell_exec("convert " . ASSETS_PATH_W . 'user/uploads/' . $getUploadedFileName . " -alpha set -bordercolor white -border 1 -fill none -fuzz 10% -draw 'color 0,0 floodfill' -shave 1x1 " . ASSETS_PATH_W . 'user/' . $outputFile);
			$src = ASSETS_PATH_W . 'user/uploads/' . $getUploadedFileName;
			$dest = ASSETS_PATH_W . 'user/' . $outputFile;

			$this->convertImage($src, $dest, $type);
			$jsonResponse = [
				'status' => 1,
				'message' => message('User Image', 'saved'),
				'data' => [
					'file_name' => $outputFile,
					'url' => path('read', 'user') . $outputFile,
				],
			];
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * Post: Save Browser Images
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author satyabratap@riaxe.com
	 * @date   4 May 2019
	 * @return A JSON Response
	 */
	public function saveBrowserImages($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'message' => message('Browser Image', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$customerId = (int)$allPostPutVars['customer_id'] ? $allPostPutVars['customer_id'] : 1;
		$storeId = $allPostPutVars['store_id'] ? $allPostPutVars['store_id'] : 1;
		$isS3Enabled = $this->checkS3Settings($storeId);
		$cloudStorage = 0;
		$source = $allPostPutVars['source'] ? $allPostPutVars['source'] : '';
		$fileTypes = array("svg", "jpeg", "jpg", "png","gif", "bmp", "pdf", "ai", "psd", "eps");
		$ext = pathinfo($_FILES['upload']['name'], PATHINFO_EXTENSION);
		if ($allPostPutVars['browser_id'] != ""  && in_array(strtolower($ext), $fileTypes)) {
			$uploadedFiles = $request->getUploadedFiles();
			$fileName = null;
			if (!empty($uploadedFiles['upload'])) {
				$fileName = do_upload_aspect(
					'upload', path('abs', 'browser_image'), [], 'string'
				);
			}
			// create thumbnail separately
			//forced to check extension here as client side unable to send thumb nail image type
			if ($fileName && !empty($uploadedFiles['thumbnail']) && in_array(strtolower($ext), $fileTypes)) {
				$thumbnailFile = (string) do_upload_aspect(
					'thumbnail', path('abs', 'browser_image'), [], 'string'
				);
				rename(path('abs', 'browser_image') . $thumbnailFile, path('abs', 'browser_image') . 'thumb_' . substr($fileName, 0, strpos($fileName, ".")) . ".png");
			}

			if ($isS3Enabled) {
				$cloudStorage = 1;
				$fileToUpload = path('abs', 'browser_image') . $fileName;
				$thumbFile = path('abs', 'browser_image') . "thumb_" . substr($fileName, 0, strpos($fileName, ".")) . ".png";
				$s3Upload = $this->uploadFileToS3("browser_image", $fileToUpload, $storeId);
				if (file_exists($thumbFile)) {
					$this->uploadFileToS3("browser_image", $thumbFile, $storeId);
				}
			}
			$ImgData = [
				'user_id' => $customerId,
				'browser_id' => $allPostPutVars['browser_id'],
				'file_name' => $fileName,
				'cloud_storage' => $cloudStorage,
			];
			$saveObjData = new BrowserImages($ImgData);
			if ($saveObjData->save()) {
				$jsonResponse = [
					'status' => 1,
					'message' => message('Browser Image', 'saved'),
					'image_url' => $isS3Enabled == 1 ? $s3Upload['S3URL'] : path('read', 'browser_image') . $fileName,
				];
				if ($storeId > 1 && empty($source) && IS_HOSTED == 0) {
					$storeResponse = $this->getStoreDomainName($storeId);
					if (!empty($storeResponse)) {
						$hostname = parse_url($jsonResponse['image_url'], PHP_URL_HOST); //hostname
						$jsonResponse['image_url'] = str_replace($hostname, $storeResponse['store_url'], $jsonResponse['image_url']);
					}
				}
			}
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * Get: Get Browser Images
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author satyabratap@riaxe.com
	 * @date   4 May 2019
	 * @return A JSON Response
	 */
	public function getBrowserImages($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'data' => [],
			'message' => message('Browser Image', 'not_found'),
		];
		$storeId = $request->getQueryParam('store_id') ? $request->getQueryParam('store_id') : 1;
		$source = $request->getQueryParam('source') ? $request->getQueryParam('source') : '';
		if (!empty($args['id'])) {
			$browserImgId = $args['id'];
			$imgInit = new BrowserImages();
			$imgData = $imgInit->where('browser_id', $browserImgId)->get();

			if (!empty($imgData)) {
				foreach ($imgData as $imgKey => $images) {
					$fileName = '';
					$thumbnail = '';
					if ($storeId > 1 && empty($source) && IS_HOSTED == 0) {
						$storeResponse = $this->getStoreDomainName($storeId);
						$hostName = parse_url($images['file_name'], PHP_URL_HOST); //hostname
						$fileName = str_replace($hostName, $storeResponse['store_url'], $images['file_name']);
						$thumbnail = str_replace($hostName, $storeResponse['store_url'], $images['thumbnail']);
					}
					$imageArr =  $images->toArray();
					if ($imageArr['cloud_storage'] == 1) {
						$thisFileName = $imageArr['file_name'];
						$thisThumbnail = $imageArr['thumbnail'];
						$data[$imgKey] = [
							'browser_id' => $images['browser_id'],
							'file_name' => $this->getS3URL($thisFileName, $storeId),
							'thumbnail' => $this->getS3URL($thisThumbnail, $storeId),
						];
					} else {
						$data[$imgKey] = [
							'browser_id' => $images['browser_id'],
							'file_name' => $fileName ? $fileName : $images['file_name'],
							'thumbnail' => $thumbnail ? $thumbnail : $images['thumbnail'],
						];
					}
				}
				$jsonResponse = [
					'status' => 1,
					'data' => $data,
				];
			}
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * @param $source  String
	 * @param $destination  String
	 * @param $action  String
	 * @author chandrakanta@riaxe.com
	 * @date   1 Oct 2020
	 * @return Array
	 */
	public function convertImage($source, $destination, $action)
	{
		switch ($action) {
			case 'removed_white':
				$command = 'convert ' . $source . ' -fuzz 10% -transparent White ' . $destination . '';
				break;
			case 'removed_edges':
				$command = 'convert ' . $source . ' -alpha set -bordercolor white -border 1 -fill none -fuzz 3% -draw "color 0,0 floodfill" -shave 1x1 ' . $destination . '';
				break;
			case 'fill_outline':
				$command = 'convert \( ' . $source . ' -trim +repage -bordercolor white -border 50 -fuzz 5% -fill none -draw "matte 0,0 floodfill" -alpha off -write mpr:img -alpha on -alpha extract -morphology dilate disk:20 -blur 0x1 -level 0x50% -write mpr:msk1 +delete \) \( mpr:msk1 -negate -fill white -opaque black -blur 0x10 -fill white -opaque white -write mpr:msk2 +delete \) \( mpr:msk1 -morphology edgein diamond:1 -negate -write mpr:edg +delete  \) mpr:img mpr:msk1 -alpha off -compose copy_opacity -composite mpr:msk2 -reverse -compose over -composite mpr:edg -compose multiply -composite -trim -alpha set -bordercolor white -border 1 -fill none -fuzz 3% -draw "color 0,0 floodfill" -shave 1x1 ' . $destination . '';
				break;
			default:
				die('please select valid options');
				break;
		}
		shell_exec($command);
		return;
	}
	/**
	 * @author Tapas
	 * @date   1 Feb 2021
	 * @return Array
	 */
	public function deleteBrowserImages($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Browser Image', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$dir = path('abs', 'browser_image');
		if (isset($allPostPutVars['file_name']) && $allPostPutVars['file_name'] != "") {
			$ImgData = [
				'file_name' => $allPostPutVars['file_name'],
			];
			$deleteObjData = new BrowserImages($ImgData);
			if ($deleteObjData->where('file_name', $allPostPutVars['file_name'])->delete()) {
				$image_location = $dir . "/" . $allPostPutVars['file_name'];
				$image_location_thumb = $dir . "/thumb_" . $allPostPutVars['file_name'];
				delete_file($image_location);
				delete_file($image_location_thumb);
				$jsonResponse = [
					'status' => 1,
					'message' => message('Browser Image', 'deleted'),
				];
			}
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * POST: Remove background
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soumyas@riaxe.com
	 * @date   19 July 2022
	 * @return A JSON Response
	 */
	public function removeBackground($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Background remove image', 'error'),
		];
		$dir =  path('abs', 'remove_background');
		if (!is_dir($dir)) {
			mkdir($dir, 0755, true);
		}
		$allPostPutVars = $request->getParsedBody();
		$fileUrl =  $allPostPutVars['file_url'];
		$getStoreDetails = get_store_details($request);
		$storeId =  $getStoreDetails['store_id'];
		$isS3Enabled = $this->checkS3Settings($storeId);
		$cloudStorage = 0;
		if (isset($fileUrl) && !empty($fileUrl)) {
			$path = parse_url($fileUrl, PHP_URL_PATH);
			$originalName =  basename($path);
			$browserImageInit = new BrowserImages();
			$getBrowserImage = $browserImageInit->select('cloud_storage')->where(['file_name' => $originalName])->first();
			if (!empty($getBrowserImage) > 0) {
				$cloudStorage = $getBrowserImage['cloud_storage'];
			}
			if ($cloudStorage == 1) {
				file_put_contents(path('abs', 'browser_image') . '/' . $originalName, fileGetContentsCurl($fileUrl));
			}
			$filePullPath = path('abs', 'browser_image') . $originalName;
			$fileSize = filesize($filePullPath);
			$fileSize = round($fileSize / 1024, 2); // Get file size in KB
			if ($fileSize >= 500) {
				create_thumb_aspect($filePullPath, $originalName, $dir, [500]);
				$originalFile = path('abs', 'remove_background') . 'thumb_' . $originalName;
			} else {
				$originalFile = path('abs', 'browser_image') . $originalName;
			}
			$withoutExtension = pathinfo($originalName, PATHINFO_FILENAME);
			$outputFile =  path('abs', 'remove_background') . 'rembg_' . $withoutExtension . '.png';
			if (!file_exists($outputFile)) {
				$shellResponse =  $this->getShellEnabledFunction();
				if ($shellResponse['status'] == 1) {
					$command = 'backgroundremover -i "' . $originalFile . '" -m "u2netp" -o "' . $outputFile . '"';
					shell_exec($command);
					if ($isS3Enabled) {
						$s3Upload = $this->uploadFileToS3("remove_background", $outputFile, $storeId);
						$imageData = ['original_file_url' => $fileUrl, 'rembg_file_url' => $s3Upload['S3URL']];
					} else {
						$imageData = ['original_file_url' => $fileUrl, 'rembg_file_url' => path('read', 'remove_background') . 'rembg_' . $withoutExtension . '.png'];
					}
					$jsonResponse = ['status' => 1, 'data' => $imageData];
				} else {
					$jsonResponse = ['status' => 0, 'message' => 'Shell script disable in your server'];
				}
			} else {
				$imageData = ['original_file_url' => $fileUrl, 'rembg_file_url' => path('read', 'remove_background') . 'rembg_' . $withoutExtension . '.png'];
				$jsonResponse = ['status' => 1, 'data' => $imageData];
			}
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * GET: Check enabled/disabled function in server(php.ini file)
	 *
	 * @author soumyas@riaxe.com
	 * @date   19 July 2022
	 * @return array of shell enabled function
	 */
	private function getShellEnabledFunction()
	{
		$result = array();
		//default function
		$disableFunctions = ini_get("disable_functions");
		if ($disableFunctions != '') {
			$disableFunctionsArr = explode(',', rtrim($disableFunctions, ','));
		} else {
			$result['status'] = true;
			$result['value'] = 'shell_exec';
		}
		//all default function for run shell command
		$deafaultShell = array(
			"passthru",
			"exec",
			"system",
			"shell_exec",
		);
		if (!empty($disableFunctionsArr)) {
			foreach ($deafaultShell as $value) {
				if (!in_array($value, $disableFunctionsArr)) {
					$result['value'] = $value;
					$result['status'] = true;
				} else {
					$result['value'] = '';
					$result['status'] = false;
				}
			}
		}
		return $result;
	}

	/**
	 * POST: Generate Embroidery Preview 
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author malay@riaxe.com
	 * @date   29th June 2022
	 * @return json response wheather data is saved or any error occured
	 */
	public function generateEmbroidery($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Embroidery preview generation', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$storeId = $allPostPutVars['store_id'] ? $allPostPutVars['store_id'] : 1;
		$source = $allPostPutVars['source'] ? $allPostPutVars['source'] : '';
		$height = $allPostPutVars['height'];
		$width = $allPostPutVars['width'];
		$format = strtolower($allPostPutVars['format']);
		$originalFilePath = $originalFileUrl = '';

		$settingInit = new Setting();
		$wilcomSettings =  $settingInit->select('setting_value')->where([
			'store_id' => $storeId,
			'setting_key' => 'wilcom'
		]);
		if ($wilcomSettings->count() > 0) {
			$wilcomSettingsData = json_clean_decode($wilcomSettings->first(), true);
			$wilcomSettingsData = json_clean_decode($wilcomSettingsData['setting_value'], true);
			if ($wilcomSettingsData['is_enabled']) {
				$getUploadedFileName = do_upload('userfile', path('abs', 'user'), [100], 'string');
				$originalFileUrl = path('read', 'user') . $getUploadedFileName;
				$AppId = $wilcomSettingsData['app_id'];
				$AppKey = $wilcomSettingsData['app_key'];
				if (!empty($getUploadedFileName)) {
					$imageFile = path('abs', 'user') . $getUploadedFileName;
					$imagedata = file_get_contents($imageFile);
					$base64 = urlencode(base64_encode($imagedata));

					$RequestXml = '<?xml version="1.0" encoding="utf-8"?>
					<xml xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
							 <bitmap file="logo_original.png" remove_background="false" /> 
							 <autodigitize_options width="' . $width . '" height="' . $height . '" thread_file="" /> 					    
							 <output trueview_file="ResultImage.png" design_file="ResultImage.' . $format . '" dpi="128" />
							 <files>
									<file filename="logo_original.png" filecontents="' . $base64 . '" filecontentmode="base64encoding" />            
							 </files>
						</xml>';

					$data = 'AppId=' . $AppId . '&AppKey=' . $AppKey . '&RequestXml=' . $RequestXml;
					$curl = curl_init();
					curl_setopt_array(
						$curl,
						array(
							CURLOPT_URL => "http://ewa.wilcom.com/4.5a/api/bitmapArtDesign",
							CURLOPT_RETURNTRANSFER => true,
							CURLOPT_ENCODING => "",
							CURLOPT_MAXREDIRS => 10,
							CURLOPT_TIMEOUT => 500,
							CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
							CURLOPT_CUSTOMREQUEST => "POST",
							CURLOPT_POSTFIELDS => $data,
							CURLOPT_HTTPHEADER => array("Content-Type: application/x-www-form-urlencoded"),
						)
					);
					$result = curl_exec($curl);
					$xml = simplexml_load_string($result);
					$json = json_encode($xml);
					$imageArray = json_decode($json, TRUE);
					$previewContent = $imageArray['files']['file'][0]['@attributes']['filecontents'];
					$realImage = ($format == 'dst')
						? $imageArray['files']['file'][2]['@attributes']['filecontents']
						: $imageArray['files']['file'][1]['@attributes']['filecontents'];
					if (!empty($previewContent) && !empty($realImage)) {
						$randomString = getRandom();
						$machineFile = path('abs', 'embroidery') . $randomString . '.' . $format;
						$previewFile = path('abs', 'embroidery') . $randomString . '.png';

						$status = file_put_contents($machineFile, base64_decode($realImage));
						if ($status) {
							file_put_contents($previewFile, base64_decode($previewContent));
							$jsonResponse = [
								'status' => 1,
								'message' => message('User Image', 'saved'),
								'data' => [
									'file_name' => $getUploadedFileName,
									'original_file_url' => $originalFileUrl,
									'thumb' => "thumb_" . $getUploadedFileName,
									'url' => path('read', 'user') . $getUploadedFileName,
									'embroidery_preview' => path('read', 'embroidery') . $randomString . '.png',
									'embroidery_machine' => path('read', 'embroidery') . $randomString . '.' . $format,
									'embroidery_data' 	=> $imageArray['design_info']['@attributes'],
								],
							];
						}
						if ($storeId > 1 && empty($source) && IS_HOSTED == 0) {
							$storeResponse = $this->getStoreDomainName($storeId);
							if (!empty($storeResponse)) {
								$hostname = parse_url($jsonResponse['data']['url'], PHP_URL_HOST); //hostname
								$jsonResponse['data']['url'] = str_replace($hostname, $storeResponse['store_url'], $jsonResponse['data']['url']);
							}
						}
						$isS3Enabled = $this->checkS3Settings($storeId);
						if ($isS3Enabled) {
							$fileToUpload = path('abs', 'user') . $getUploadedFileName;
							$s3Upload = $this->uploadFileToS3("user", $fileToUpload, $storeId);
							if (!empty($originalFilePath)) {
								$s3UploadOrgFile = $this->uploadFileToS3("user", $originalFilePath, $storeId);
								$jsonResponse['data']['original_file_url'] = $s3UploadOrgFile['S3URL'];
							}
							if ($s3Upload['error'] == 0) {
								$jsonResponse['data']['url'] = $s3Upload['S3URL'];
							}
						}
					} else {
						$jsonResponse = [
							'status' => 0,
							'message' => 'Unable to generate preview file',
						];
					}
				} else {
					$jsonResponse = [
						'status' => 0,
						'message' => 'Unable to generate preview file',
					];
				}
			} else {
				$jsonResponse = [
					'status' => 0,
					'message' => 'Wilcom is not integrated',
				];
			}
		} else {
			$jsonResponse = [
				'status' => 0,
				'message' => 'Wilcom is not integrated',
			];
		}

		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * POST: Generate Embroidery Preview 
	 *
	 * @param $sourcePath  Image source path
	 * @param $destinationPath Image Destination path
	 *
	 * @author steve@imprintnext.com
	 * @date   12 Dec 2022
	 * @return 
	 */
	function phpImageMagicTypeConvert($sourcePath, $destinationPath)
	{
		$imagick = new \Imagick($sourcePath);
		$format = $imagick->getImageFormat();
		if ($format == 'EPT' || $format == 'EPS') {
			$tempfile = explode('user/', $destinationPath);
			$imageDir = $tempfile[0] . 'user/';
			$filename =  explode(".", $tempfile[1]);

			// For proper conversion Ghost script 10 and imagick 7.1.1-4 needed
			shell_exec('convert -colorspace sRGB -density 300 ' . $sourcePath . ' ' . $destinationPath . ' && mv ' .  $imageDir . $filename[0] . "-0.png " . $destinationPath);
			unlink($imageDir . $filename[0] . "-1.png ");

			//if file not generated using new script then we will generate by old phpimagick method.
			if (!file_exists($destinationPath)) {
				$resolution =  $imagick->getImageGeometry();
				$width = (int)$resolution['width'] + 10;
				$height = (int)$resolution['height'] + 10;
				$imagick->scaleImage($width, $height);
				$imagick->setImageFormat("png");
				$imagick->writeImage($destinationPath);
				$imagick->clear();
				$imagick->destroy();
			}
		} else {
			if ($format == 'GIF') {
				$imagick = $imagick->coalesceImages();
				$imagick = $imagick->deconstructImages();
			}
			$imagick->setImageFormat("png");
			$imagick->writeImage($destinationPath);
			$imagick->clear();
			$imagick->destroy();
		}
	}
}
