<?php

/**
 * Manage Color Palette
 *
 * PHP version 5.6
 *
 * @category  ColorPalettes
 * @package   Assets
 * @author    Debashri Bhakat <debashrib@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\ColorPalettes\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Dependencies\Zipper as Zipper;
use App\Modules\ColorPalettes\Models\ConfiguratorColor;
use App\Modules\ColorPalettes\Models\ConfigurColorCategory as Category;
use Illuminate\Database\Capsule\Manager as DB;
use Intervention\Image\ImageManagerStatic as ImageManager;

/**
 * ColorPalettes Controller
 *
 * @category ColorPalettes
 * @package  Assets
 * @author   Debashri Bhakat <debashrib@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */

class ConfiguratorColorController extends ParentController
{
	/**
	 * Initiate Constructer function
	 */
	public function __construct()
	{
		DB::enableQueryLog();
	}

	/**
	 * Get: Single ColorPalette Details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author dan@imprintnext.com
	 * @date   21-07-2022
	 * @return json
	 */
	public function getSingleColor($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'data' => [],
			'message' => message('Color', 'error')
		];
		// get the store id
		$getStoreDetails = get_store_details($request);
		$storeId = $getStoreDetails['store_id'];

		if (!empty($args['id'])) {
			$colorPaletteId = to_int($args['id']);
			$colorPaletteInit = new ConfiguratorColor();
			$getProcessedColors = $colorPaletteInit->join(
				'categories',
				'configurator_colors.category_id',
				'=',
				'categories.xe_id'
			)->select([
				'configurator_colors.xe_id',
				'configurator_colors.category_id',
				'configurator_colors.name',
				'configurator_colors.price',
				'configurator_colors.value',
				'configurator_colors.hex_value',
				'categories.name as cat_name',
				'configurator_colors.cloud_storage'
			])->where('configurator_colors.xe_id', '=', $colorPaletteId);

			if ($getProcessedColors->count() > 0) {
				$processedColors = $getProcessedColors->get()->first()->toArray();
				$colorType = empty($processedColors['hex_value']) ? 'pattern' : 'color';
				$processedColors['color_type'] = $colorType;

				if ($colorType == 'pattern') {
					$fileName = path('read', 'configurcolors')  . $processedColors['value'];
					$thumbValue = path('read', 'configurcolors') . 'thumb_' . $processedColors['value'];
					if ($processedColors['cloud_storage'] == 1) {
						$fileName =  $this->getS3URL($fileName, $storeId);
						$thumbValue = $this->getS3URL($thumbValue, $storeId);
					}
					$processedColors['file_name'] = $thumbValue;
					$processedColors['value'] = $fileName;
				}

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

	/**
	 * Get: Get ColorPalette(s) Details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author debashrib@riaxe.com
	 * @date   05 Dec 2019
	 * @return json
	 */
	public function getColors($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'data' => [],
			'message' => message('Color', 'error')
		];
		$storeId = $request->getQueryParam('store_id');
		if (empty($storeId)) {
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];
		}
		$page = 1;
		$perpage = 20;
		
		$otherFilterData = [];
		$finalData = [];
		
		//GET MEMCACHEDATA
		$memcacheData = [];
		if (!empty($storeId)) {
			
			//MEMCACHED KEY
			$thisCacheKey = "colorpalette" ."_s" . $storeId;
			
			if (IS_MEMCACHE) {
				//Register MEMCACHED KEY in Local Cache
				$this->createUpdateMemCacheGroup('configurcolors', $thisCacheKey, 'SET');
				$memcacheData = $this->memcache("get", $thisCacheKey);
			}
		}
		if (empty($memcacheData)) {
			$categoryInit = new Category();
			$assetTypeArr = $categoryInit->AssetsTypeId();
			if ($assetTypeArr['status'] == 1) {
				$assetTypeId = $assetTypeArr['asset_type_id'];
				// Collect all filter parameters
				$catagoryId = ($request->getQueryParam('cat_id') != '') ?
				$request->getQueryParam('cat_id') : 0;
				$keyword = ($request->getQueryParam('keyword') ?
				$request->getQueryParam('keyword') : '');
				$sortBy = $request->getQueryParam('sortby');
				$order = $request->getQueryParam('order');
				$page = ($request->getQueryParam('page') != '') ? $request->getQueryParam('page') : 1;
				$colorPage = ($request->getQueryParam('color_page') != '') ? $request->getQueryParam('color_page') : 1;
				$perpage = ($request->getQueryParam('perpage') != '') ? $request->getQueryParam('perpage') : 10;
				
				$sortingData = $request->getQueryParam('sorting');
				$isAdmin = ($request->getQueryParam('is_admin') != '')
				? $request->getQueryParam('is_admin') : 0;
				
				// Filter by category ID
				if (!empty($catagoryId)) {
					$configColorCats = json_clean_decode($catagoryId, true);
					$getCategory = $categoryInit->select(['xe_id', 'name', 'is_defined', 'is_disable'])->where(['store_id' => $storeId])->whereIn('xe_id', $configColorCats);
				} else {
					$conditions = ['store_id' => $storeId, 'parent_id' => 0, 'asset_type_id' => $assetTypeId];
					$getCategory = $categoryInit->select(['xe_id', 'name', 'is_defined', 'is_disable'])->where($conditions);
				}
				$getCategory->orderBy('sort_order', 'asc');
				$totalRecord = count($getCategory->get()->toArray());
				if ($page != "") {
					$totalItem = empty($perpage) ? 10 : $perpage;
					$offset = $totalItem * ($page - 1);
					$getCategory->skip($offset)->take($totalItem);
				}
				// get all the matching categories
				$getCategory = $getCategory->get()->toArray();
				// Other filter data
				$otherFilterData = [
					'keyword' => $keyword,
					'sortBy' => $sortBy,
					'order' => $order,
					'store_id' => $storeId
				];

				if (!empty($getCategory)) {
					foreach ($getCategory as $catValue) {
						$finalData[] = [
							"cat_id" => $catValue['xe_id'],
							"cat_name" => $catValue['name'],
							"is_defined" => $catValue['is_defined'],
							"is_disable" => $catValue['is_disable'],
							"category" => $this->_getSubcategoryData(
								(empty($subCatIds) ? array($catValue['xe_id']) : $subCatIds),
								$catValue['name'],
								$otherFilterData,
								$sortingData,
								$isAdmin,
								$perpage,
								$colorPage
							)
						];
					}

					$jsonResponse = ['status' => 1, 'data' => $finalData, 'total_records' => $totalRecord];
				}
			}
			//SET IN MEMCACHED
			if (IS_MEMCACHE and isset($thisCacheKey)) {
				$this->memcache("set", $thisCacheKey, $jsonResponse);
			}
		} else {
			$jsonResponse = $memcacheData;
			if (MEM_MODE) {
				$jsonResponse['mode'] = 'memcache';
			}
		}
		if ($args['return']) {
			return $finalData;
		}else{
			return response($response, [
				'data' => $jsonResponse,
				'status' => $serverStatusCode
			]);
		}

	}

	/**
	 * Getting subcategory w.r.t category
	 *
	 * @param $subcatIds       Subcat id
	 * @param $catName         category name
	 * @param $otherFilterData data to filter
	 *
	 * @author debashrib@riaxe.com
	 * @date   05 Dec 2019
	 * @return array of subcategory
	 */
	private function _getSubcategoryData($subcatIds, $catName, $otherFilterData, $sortingData, $isAdmin, $perpage, $colorPage)
	{
		$subcategory = [];
		$sortingData = json_decode($sortingData, true);
		
		$categoryInit = new Category();
		$getSubcatQuery = $categoryInit->where('is_disable', 0)->select('xe_id', 'name', 'parent_id');
		
		$getSubcatQuery->whereIn('xe_id', $subcatIds);
		
		
		// there should exist profile for the category - when print profile is supplied
		
		$getSubcatQuery->orderBy('sort_order', 'asc');
		
		if ($getSubcatQuery->count() > 0) {
			$getSubcategories = $getSubcatQuery->get()->toArray();
			foreach ($getSubcategories as $value) {
				if (!empty($sortingData)) {
					foreach ($sortingData as $valueSort) {
						if ($valueSort['sub_id'] == $value['xe_id']) {
							$colorPage = $valueSort['page_no'];
							$perpage = !empty($valueSort['per_page']) ? $valueSort['per_page'] : '';
						} elseif (!$isAdmin) {
							$colorPage = $perpage = "";
						} 
						$colorData = $this->_getColorData(
							$value['xe_id'],
							$catName,
							$otherFilterData,
							$colorPage,
							$perpage
						);
						$totalRec = $colorData['totalCount'];
						unset($colorData['totalCount']);
						$subcategory[] = [
							'subcat_id' => $value['xe_id'],
							'subcat_name' => $value['name'],
							'total_record' => $totalRec,
							'color_data' => $colorData,
						];
					}
				} else {
					// no pagination requested
					if (!$isAdmin) {
						$$colorPage = $perpage = "";
					} 
					$colorData = $this->_getColorData(
						$value['xe_id'],
						$otherFilterData,
						$colorPage,
						$perpage
					);
					$totalRec = $colorData['totalCount'];
					unset($colorData['totalCount']);
					$subcategory[] = [
						'subcat_id' => $value['xe_id'],
						'subcat_name' => $value['name'],
						'total_record' => $totalRec,
						'color_data' => $colorData
					];
				}
			}
		}
		return $subcategory;
	}

	/**
	 * Getting color data w.r.t category and subcategory
	 *
	 * @param $catId           category id
	 * @param $catName         category name
	 * @param $otherFilterData data to filter
	 *
	 * @author debashrib@riaxe.com
	 * @date   05 Dec 2019
	 * @return array of color data
	 */
	private function _getColorData($catId, $otherFilterData, $page, $perpage)
	{
		$colordata = [];
		$colorPaletteInit = new ConfiguratorColor();
		$getColor = $colorPaletteInit->select([
			'xe_id',
			'name',
			'price',
			'value',
			'hex_value',
			'cloud_storage'
		])->where([
			['xe_id', '>', 0],
			['category_id', '=', $catId]
		]);
		// fiter by keyword
		if (!empty($otherFilterData['keyword'])) {
			$getColor->where(
				function ($query) use ($otherFilterData) {
					$query->where('name', 'LIKE', '%' . $otherFilterData['keyword'] . '%')
						->orwhere('hex_value', 'LIKE', '%' . $otherFilterData['keyword'] . '%');
				}
			);
		}
		// fiter by store id
		if (!empty($otherFilterData['store_id'])) {
			$getColor->where('store_id', $otherFilterData['store_id']);
		}
		// total records
		$getTotalPerFilters = $getColor->count();
		// pagination
		if ($page != "") {
			$totalItem = empty($perpage) ? 10 : $perpage;
			$offset = $totalItem * ($page - 1);
			$getColor->skip($offset)->take($totalItem);
		}
		// sort by filter
		if (!empty($otherFilterData['sortBy']) && !empty($otherFilterData['order'])) {
			$getColor->orderBy($otherFilterData['sortBy'], $otherFilterData['order']);
		} else {
			$getColor->orderBy('xe_id', 'DESC');
		}
		// get the colors and format
		$getColorRecords = $getColor->get();

		if (!empty($getColorRecords)) {
			foreach ($getColorRecords as $value) {
				$colorType = empty($value->hex_value) ? 'pattern' : 'color';

				// get the pattern file
				$colorValue = '';
				if ($colorType == 'pattern') {
					if ($value['cloud_storage'] == 1) {
						$color = path('abs', 'configurcolors') . 'thumb_' . $value->value;
						$colorValue = $this->getS3URL($color, $otherFilterData['store_id']);
					} else {
						$colorValue = path('read', 'configurcolors') . 'thumb_' . $value->value;
					}
				}

				$colordata[] = [
					'id' => $value->xe_id,
					'name' => $value->name,
					'price' => $value->price,
					'value' => $colorValue,
					'hex_value' => !empty($value->hex_value) ? $value->hex_value : '',
					'color_type' => $colorType,
					'cloud_storage' => $value->cloud_storage
				];
			}
		}
		$colordata["totalCount"] = $getTotalPerFilters;
		return $colordata;
	}

	/**
	 * Check if the record exists according to the category and print profiles
	 *
	 * @param $categoryId Category id
	 * @param $profileKey Print Profile Ids in a array format
	 *
	 * @author tanmayap@riaxe.com
	 * @date   27 Feb 2020
	 * @return boolean
	 */
	public function checkInPrintProfile($categoryId, $profileKey)
	{
		if (!empty($categoryId)) {
			$profileCatRelObj = new \App\Modules\PrintProfiles\Models\PrintProfileAssetsCategoryRel();
			$assetTypeArr = $this->assetsTypeId('color-palettes');
			$profileCatRelDetails = $profileCatRelObj->where([
				'asset_type_id' => $assetTypeArr['asset_type_id'],
				'category_id' => $categoryId
			])->whereIn('print_profile_id', $profileKey);
			if ($profileCatRelDetails->count() > 0) {
				return true;
			}
		}
		return false;
	}
	/**
	 * POST: Save ColorPalette Data
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author debashrib@riaxe.com
	 * @date   06 Dec 2019
	 * @return json response wheather data is saved or any error occured
	 */
	public function saveColors($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Color', 'error')
		];

		$allPostPutVars = $request->getParsedBody();
		$getStoreDetails = get_store_details($request);

		if (!empty($allPostPutVars)) {
			// If any file exist then upload
			$fileName = do_upload(
				'upload',
				path('abs', 'configurcolors'),
				[150],
				'string'
			);

			$uploadedFilePath = path('abs', 'configurcolors') . $fileName;
			$uploadFileExt = pathinfo($fileName, PATHINFO_EXTENSION);
			$storeId = $allPostPutVars['store_id'] = $getStoreDetails['store_id'];
			$catId = $allPostPutVars['category_id'];

			if ($uploadFileExt == 'csv' && !empty($fileName)) {
				try {
					// function to save data from csv
					$colorLastInsertId = $this->_saveCSVData(
						$storeId,
						$catId,
						$uploadedFilePath
					);
				} catch (\Exception $e) {
					$serverStatusCode = EXCEPTION_OCCURED;
					create_log('color', 'error', [
						'message' => $e->getMessage(),
						'extra' => [
							'module' => 'Import data by CSV file'
						]
					]);
				}
			} elseif ($uploadFileExt == 'zip' && !empty($fileName)) {
				try {
					// function to save data from zip
					$colorLastInsertId = $this->_saveZipData(
						$storeId,
						$catId,
						$uploadedFilePath
					);
				} catch (\Exception $e) {
					$serverStatusCode = EXCEPTION_OCCURED;
					create_log('color', 'error', [
						'message' => $e->getMessage(),
						'extra' => [
							'module' => 'Import data by ZIP file'
						]
					]);
				}
			} else {
				try {
					// During pattern file uploading, this code will run
					if (!empty($uploadFileExt) && !empty($uploadedFilePath)) {
						//file upload in S3
						$isS3Enabled = $this->checkS3Settings($getStoreDetails['store_id']);
						if ($isS3Enabled) {
							$thumbFile = path('abs', 'configurcolors') . "thumb_" . $fileName;
							$fileToUpload = path('abs', 'configurcolors') . $fileName;
							$this->uploadFileToS3("colorpalette", $thumbFile, $getStoreDetails['store_id']);
							$this->uploadFileToS3("colorpalette", $fileToUpload, $getStoreDetails['store_id']);
							$allPostPutVars['cloud_storage'] = 1;
						}
						$allPostPutVars['value'] = $fileName;
					}
					$color = new ConfiguratorColor($allPostPutVars);
					$color->save();
					$colorLastInsertId = $color->xe_id;
				} catch (\Exception $e) {
					$serverStatusCode = EXCEPTION_OCCURED;
					create_log('color', 'error', [
						'message' => $e->getMessage(),
						'extra' => [
							'module' => 'Saving a color data'
						]
					]);
				}
			}
		}
		if (!empty($colorLastInsertId)) {
			$jsonResponse = [
				'status' => 1,
				'message' => message('Color', 'saved'),
				'color_id' => $colorLastInsertId
			];
		}
		$allPostPutVars['categories'] = '[' . $allPostPutVars['category_id'] . ']';
		

		// Flush Colors memcached
		$this->memcache('deleteMulti', '', '', 'configurcolors');
		return response($response, [
			'data' => $jsonResponse,
			'status' => $serverStatusCode
		]);
	}

	/**
	 * Saving data from csv file
	 *
	 * @param $storeId  Store_Id
	 * @param $catId    Category_Id
	 * @param $filePath csv file path
	 *
	 * @author debashrib@riaxe.com
	 * @date   06 Dec 2019
	 * @return last inserted id
	 */
	private function _saveCSVData($storeId, $catId, $filePath)
	{
		try {
			$categoryInit = new Category();
			$getCategory = $categoryInit->find($catId);
			$catName = $getCategory->name;
			$file = fopen($filePath, "r");
			$csvData = [];
			$loop = 0;
			$colorLastInsertId = 0;
			while (($column = fgetcsv($file, 10000, ",")) !== false) {
				if ($loop != 0) {
					//Check duplicate color
					$colorInit = new ConfiguratorColor();
					$checkColor = $colorInit->where([
						'category_id' => $catId,
						'hex_value' => $column[1]
					]);
					if ($checkColor->count() == 0) {
						if ($catName == 'CMYK') {
							$value = $column[3] . ',' . $column[4]
								. ',' . $column[5] . ',' . $column[6];
						} elseif ($catName == 'RGB') {
							$value = $column[3] . ',' . $column[4] . ',' . $column[5];
						} elseif (
							$catName == 'Pantone'
							|| $catName == 'Embroidery Thread'
						) {
							$value = $column[3];
						} else {
							$value = '';
						}
						$csvData = [
							'store_id' => $storeId,
							'category_id' => $catId,
							'name' => $column[0],
							'hex_value' => $column[1],
							'price' => (isset($column[2]) && $column[2] != "")
								? $column[2] : 0,
							'value' => $value
						];


						// Save Color Data
						$color = new ConfiguratorColor($csvData);
						$color->save();
						$colorLastInsertId = $color->xe_id;
					} else {
						$data = $checkColor->first()->toArray();
						$colorLastInsertId = $data['xe_id'];
					}
				}
				$loop++;
			}
			fclose($file);
			if (!empty($colorLastInsertId) && file_exists($filePath)) {
				unlink($filePath);
			}
		} catch (\Exception $e) {
			create_log('color', 'error', [
				'message' => $e->getMessage(),
				'extra' => [
					'module' => 'Saving CSV color data'
				]
			]);
		}
		return $colorLastInsertId;
	}

	/**
	 * Saving data from zip file
	 *
	 * @param $storeId     Store_Id
	 * @param $catId       Category_Id
	 * @param $subcatId    Subcategory_Id
	 * @param $zipFilePath zip file path
	 *
	 * @author debashrib@riaxe.com
	 * @date   07 Dec 2019
	 * @return last inserted id
	 */
	private function _saveZipData($storeId, $catId, $zipFilePath)
	{
		$categoryInit = new Category();
		$getCategory = $categoryInit->find($catId);
		$catName = $getCategory->name;

		// return if category is not pattern
		if ($catName != 'Pattern') {
			return 0;
		}

		$colorLastInsertId = 0;
		$imagesPath = path('abs', 'configurcolors');
		$zipExtractedPath = $imagesPath . uniqid(
			'zipextract' . date('Ymdhis') . '-'
		);
		if (!is_dir($zipExtractedPath)) {
			mkdir($zipExtractedPath, 0777, true);
		}
		shell_exec('chmod -R 777 ' . $zipExtractedPath);
		$zip = new Zipper();
		$zipStatus = $zip->make($zipFilePath);
		if ($zipStatus) {
			$zip->extractTo($zipExtractedPath);
		}
		$rawCsvFilePathArr = glob($zipExtractedPath . "/*.csv");
		$rawCsvFilePath = $rawCsvFilePathArr[0];
		if (!empty($rawCsvFilePath)) {
			$file = fopen($rawCsvFilePath, "r");
			$csvData = [];
			$loop = 0;
			$column = fgetcsv($file, 10000, ",");
			while (!feof($file)) {
				$column = fgetcsv($file);
				if ($loop >= 0) {
					$imagePathArr = glob($zipExtractedPath . "/" . $column[2]);
					$patterImgPath = $imagePathArr[0];
					$patternImg = getRandom() . $column[2];
					$newPatterImgPath = $imagesPath . $patternImg;
					// copy patter image file from extreacted folder to root
					// folder
					$isS3Enabled = $this->checkS3Settings($storeId);

					if (copy($patterImgPath, $newPatterImgPath)) {
						// creating thumb file
						$convertToSize = [100];
						$imageManagerInit = new ImageManager();
						$img = $imageManagerInit->make($newPatterImgPath);
						foreach ($convertToSize as $dimension) {
							$img->resize($dimension, $dimension);
							$img->save($imagesPath . 'thumb_' . $patternImg);
						}
						if ($isS3Enabled) {
							$fileToUpload = $imagesPath . $patternImg;
							$thumbUpload = $imagesPath . 'thumb_' . $patternImg;
							$this->uploadFileToS3("colorpalette", $fileToUpload, $storeId);
							$this->uploadFileToS3("colorpalette", $thumbUpload, $storeId);
						}

						// Creating a Associative array which contains the
						// Database row for inserting into the DB
						$csvData = [
							'store_id' => $storeId,
							'category_id' => $catId,
							'name' => $column[0],
							'price' => (isset($column[1]) && $column[1] != "")
								? $column[1] : 0,
							'cloud_storage' => ($isS3Enabled ? 1 : 0),
							'value' => $patternImg
						];
						// Save Color Data
						$color = new ConfiguratorColor($csvData);
						$color->save();
						$colorLastInsertId = $color->xe_id;
					}
				}
				$loop++;
			}
		}
		$zip->close();
		fclose($file);
		if (!empty($colorLastInsertId)) {
			// delete zip file
			if (file_exists($zipFilePath)) {
				unlink($zipFilePath);
			}
			// remove extracted zip folder with file inside it
			if (file_exists($zipExtractedPath)) {
				array_map('unlink', glob("$zipExtractedPath/*.*"));
				rmdir($zipExtractedPath);
			}
		}

		return $colorLastInsertId;
	}


	/**
	 * PUT: Update a single ColorPalette
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author debashrib@riaxe.com
	 * @date   07 Dec 2019
	 * @return json response wheather data is updated or not
	 */
	public function updateColor($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Color', 'error')
		];
		try {
			if (!empty($args['id'])) {

				$colorId = to_int($args['id']);
				$getStoreDetails = get_store_details($request);
				$storeId = $getStoreDetails['store_id'];
				$updateData = $request->getParsedBody();
				$colorPaletteInit = new ConfiguratorColor();
				$getOldColor = $colorPaletteInit->where('xe_id', $colorId)->get()->first()->toArray();

				if (!empty($getOldColor)) {
					// do not update the color when no hex value present
					if (empty($updateData['hex_value'])) {
						unset($updateData['value']);
					}

					if ($request->getUploadedFiles()) {
						// Process file uploading
						$getUploadedFileName = do_upload(
							'upload',
							path('abs', 'configurcolors'),
							[150],
							'string'
						);

						if ($getOldColor['cloud_storage'] == 1) {
							// delete old file from the cloud
							$file = path('abs', 'configurcolors') . $getOldColor['value'];
							$thumbnail = path('abs', 'configurcolors') . "thumb_" . $getOldColor['value'];
							$this->deleteS3File($file, $storeId);
							$this->deleteS3File($thumbnail, $storeId);
							// move new file to the cloud
							$thumbUpload = path('abs', 'configurcolors') . "thumb_" . $getUploadedFileName;
							$fileToUpload = path('abs', 'configurcolors') . $getUploadedFileName;
							$this->uploadFileToS3("background", $fileToUpload, $storeId);
							$this->uploadFileToS3("background", $thumbUpload, $storeId);
						} else {
							// delete old file from the server
							$this->deleteOldFile(
								'color_palettes',
								'value',
								['xe_id' => $colorId],
								path('abs', 'configurcolors'),
								false
							);
						}

						$updateData['value'] = $getUploadedFileName; // 'value' - holds the file
					}

					$updateData['store_id'] = $storeId;
					// Update record
					$colorPaletteInit->where('xe_id', $colorId)->update($updateData);
					$updateData['categories'] = '[' . $updateData['category_id'] . ']';
					
					$jsonResponse = [
						'status' => 1,
						'message' => message('Color', 'updated')
					];
				}
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			create_log('color', 'error', [
				'message' => $e->getMessage(),
				'extra' => [
					'module' => 'Update color details'
				]
			]);
		}
		// Flush font memcached
		$this->memcache('deleteMulti', '', '', 'configurcolors');
		return response($response, [
			'data' => $jsonResponse,
			'status' => $serverStatusCode
		]);
	}

	/**
	 * Delete: Delete a ColorPalette
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author debashrib@riaxe.com
	 * @date   06 Dec 2019
	 * @return json
	 */
	public function deleteColor($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Color', 'error')
		];
		try {
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];

			// deletable ids
			$getDeleteIdsToArray = !empty($args['id']) ? json_clean_decode($args['id'], true) : [];
			if ($getDeleteIdsToArray) {
				$colorPaletteInit = new ConfiguratorColor();

				// hex_value is empty when file is present
				$getColorQuery = $colorPaletteInit->where('store_id', $storeId)
					->whereIn('xe_id', $getDeleteIdsToArray)
					->where(function ($q) {
						$q->where('hex_value', '=', '')->orWhereNull('hex_value');
					});

				if ($getColorQuery->count() > 0) {
					// fetch Colors having pattern files
					$getColorDetails = $getColorQuery->get()->toArray();
					// delete files from the server / cloud
					foreach ($getColorDetails as $colorFile) {
						if ($colorFile['cloud_storage'] == 1) {
							$fileName = path('abs', 'configurcolors') . $colorFile['value'];
							$thumbfile = path('abs', 'configurcolors') . "thumb_" . $colorFile['value'];
							$this->deleteS3File($fileName, $storeId);
							$this->deleteS3File($thumbfile, $storeId);
						} else {
							$this->deleteOldFile(
								"color_palettes",
								"value",
								['xe_id' => $colorFile['xe_id']],
								path('abs', 'configurcolors'),
								false
							);
						}
					}
				}
				$categoryList =  $colorPaletteInit->where('store_id', $storeId)
					->whereIn('xe_id', $getDeleteIdsToArray)
					->distinct()
					->get('category_id')->first()->toArray();

				// delete the records
				$delCount = $colorPaletteInit->where('store_id', $storeId)
					->whereIn('xe_id', $getDeleteIdsToArray)
					->delete();
				
				if ($delCount) {
					$jsonResponse = [
						'status' => 1,
						'message' => message('Color', 'deleted')
					];
				}
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			create_log('color', 'error', [
				'message' => $e->getMessage(),
				'extra' => [
					'module' => 'Delete color'
				]
			]);
		}
		// Flush color memcached
		$this->memcache('deleteMulti', '', '', 'configurcolors');
		return response($response, [
			'data' => $jsonResponse,
			'status' => $serverStatusCode
		]);
	}

	/**
	 * Delete: Delete a ColorPalette Category
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author debashrib@riaxe.com
	 * @date   04 Dec 2019
	 * @return json
	 */
	public function deleteColorCategory($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Subcategory', 'error')
		];
		try {
			if (!empty($args['id'])) {
				// get the store id
				$getStoreDetails = get_store_details($request);
				$storeId = $getStoreDetails['store_id'];
				// deletable category id
				$deleteId = to_int($args['id']);
				$categoryInit = new Category();
				$category = $categoryInit->find($deleteId);

				if (!empty($category->xe_id)) {
					// find the colorpalette belongs to the category and having file
					$colorPaletteInit = new ConfiguratorColor();
					$colorPalettes = $colorPaletteInit->where('subcategory_id', $deleteId)
						->where(function ($q) {
							$q->where('hex_value', '=', '')->orWhereNull('hex_value');
						})->get()->toArray();

					$colorIds = [];
					// delete the color palette file
					foreach ($colorPalettes as $colorFile) {
						if ($colorFile['cloud_storage'] == 1) {
							$fileName = path('abs', 'configurcolors') . $colorFile['value'];
							$thumbfile = path('abs', 'configurcolors') . "thumb_" . $colorFile['value'];
							$this->deleteS3File($fileName, $storeId);
							$this->deleteS3File($thumbfile, $storeId);
						} else {
							$this->deleteOldFile(
								"color_palettes",
								"value",
								['xe_id' => $colorFile['xe_id']],
								path('abs', 'configurcolors'),
								false
							);
						}
						$colorIds[] = $colorFile['xe_id'];
					}
					// delete the color palettes
					if ($colorIds) {
						$colorPaletteInit->whereIn('xe_id', $colorIds)->delete();
					}
					// delete the category
					$category->delete();

					$jsonResponse = [
						'status' => 1,
						'message' => message('Subcategory', 'deleted')
					];
				}
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			create_log('color', 'error', [
				'message' => $e->getMessage(),
				'extra' => [
					'module' => 'Delete color category'
				]
			]);
		}

		// Flush font memcached
		$this->memcache('deleteMulti', '', '', 'configurcolors');

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