<?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\ColorPalette;
use App\Modules\ColorPalettes\Models\ColorPaletteCategory 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 ColorPaletteController 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 ColorPalette();
			$getProcessedColors = $colorPaletteInit->join(
				'categories',
				'color_palettes.category_id',
				'=',
				'categories.xe_id'
			)->select([
				'color_palettes.xe_id',
				'color_palettes.category_id',
				'color_palettes.subcategory_id',
				'color_palettes.name',
				'color_palettes.price',
				'color_palettes.value',
				'color_palettes.hex_value',
				'categories.name as cat_name',
				'color_palettes.cloud_storage'
			])->where('color_palettes.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', 'colorpalette')  . $processedColors['value'];
					$thumbValue = path('read', 'colorpalette') . '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'];
		}
		$printProfileKey = $request->getQueryParam('print_profile_id');
		$assetCacheData = [];
		$page = 1;
		$perpage = 20;
		if (!empty($printProfileKey)) {
			$assetCacheData = $this->getAssetCache($storeId, $printProfileKey, $page, $perpage, 'colorpalette');
		}

		$otherFilterData = [];
		$finalData = [];

		//GET MEMCACHEDATA
		$memcacheData = [];
		if (!empty($printProfileKey)) {

			$printProfileId = (is_string($printProfileKey) && strlen($printProfileKey) > 1) ? json_decode($printProfileKey, true) : $printProfileKey;
			if (is_array($printProfileId)) {
				$printProfileId = $printProfileId[0];
			}

			//MEMCACHED KEY
			$thisCacheKey = "colorpalette" . "_pp" . $printProfileId . "_s" . $storeId;

			if (IS_MEMCACHE) {
				//Register MEMCACHED KEY in Local Cache
				$this->createUpdateMemCacheGroup('colorpalette', $thisCacheKey, 'SET');
				$memcacheData = $this->memcache("get", $thisCacheKey);
			}
		}
		if (empty($memcacheData)) {
			if (empty($assetCacheData)) {
				$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;
					$subCatIds = !empty($request->getQueryParam('subcat_id')) ?
						json_clean_decode($request->getQueryParam('subcat_id'), true) : [];
					$keyword = ($request->getQueryParam('keyword') ?
						$request->getQueryParam('keyword') : '');
					$sortBy = $request->getQueryParam('sortby');
					$order = $request->getQueryParam('order');
					$page = ($request->getQueryParam('page') != '') ? $request->getQueryParam('page') : 1;
					$perpage = ($request->getQueryParam('perpage') != '') ? $request->getQueryParam('perpage') : 10;

					// multiple print profile, eg: [1,2,3]
					$printProfileIds = ($request->getQueryParam('print_profile_id') ?
						json_clean_decode($request->getQueryParam('print_profile_id'), true) : []);
					$sortingData = $request->getQueryParam('sorting');
					$isAdmin = ($request->getQueryParam('is_admin') != '')
						? $request->getQueryParam('is_admin') : 0;

					// Filter by category ID
					if (!empty($catagoryId)) {
						$conditions = ['store_id' => $storeId, 'xe_id' => $catagoryId];
					} else {
						$conditions = ['store_id' => $storeId, 'parent_id' => 0, 'asset_type_id' => $assetTypeId];
					}
					$getCategory = $categoryInit->select(['xe_id', 'name', 'is_defined', 'is_disable'])->where($conditions);
					// there should exist profile for the category - when print_profile_id is supplied
					if ($printProfileIds) {
						$getCategory->whereExists(function ($query) use ($printProfileIds, $assetTypeId) {
							$query->select(DB::raw(1))
								->from('print_profile_assets_category_rel')
								->whereIn('print_profile_id', $printProfileIds)
								->where('asset_type_id', $assetTypeId);
						});
					}
					// orderby
					$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'],
								"subcategory" => $this->_getSubcategoryData(
									(empty($subCatIds) ? $catValue['xe_id'] : $subCatIds),
									$catValue['name'],
									$otherFilterData,
									$printProfileIds,
									$sortingData,
									$isAdmin
								)
							];
						}

						$jsonResponse = ['status' => 1, 'data' => $finalData, 'total_records' => $totalRecord];
					}
					if (isset($printProfileIds) && !empty($printProfileIds) && $page <= 2) {

						$assetData = $page == 1 ?
							[
								'total_records' => $totalRecord,
								'data' => $finalData
							] : $finalData;
						$this->createAssetCache('colorpalette', $storeId, $printProfileIds, $assetData, $page);
					}
				}
			} else {
				$jsonResponse = [
					'status' => 1,
					'total_records' => $assetCacheData['total_records'],
					'records' => count($assetCacheData['data']),
					'data' => $assetCacheData['data']
				];
			}
			//SET IN MEMCACHED
			if (IS_MEMCACHE and isset($thisCacheKey)) {
				$this->memcache("set", $thisCacheKey, $jsonResponse);
			}
		} else {
			$jsonResponse = $memcacheData;
			if (MEM_MODE) {
				$jsonResponse['mode'] = 'memcache';
			}
		}

		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, $printProfileIds, $sortingData, $isAdmin)
	{
		$subcategory = [];
		$sortingData = json_decode($sortingData, true);


		$categoryInit = new Category();
		$getSubcatQuery = $categoryInit->where('is_disable', 0)->select('xe_id', 'name', 'parent_id');

		if (is_array($subcatIds) && !empty($subcatIds)) {
			$getSubcatQuery->whereIn('xe_id', $subcatIds);
		} else {
			$getSubcatQuery->where('parent_id', $subcatIds);
		}

		// there should exist profile for the category - when print profile is supplied
		if ($printProfileIds) {
			$assetTypeArr = $this->assetsTypeId('color-palettes');
			$getSubcatQuery->whereExists(function ($query) use ($printProfileIds, $assetTypeArr) {
				$query->select(DB::raw(1))
					->from('print_profile_assets_category_rel')
					->whereRaw('print_profile_assets_category_rel.category_id = categories.xe_id')
					->whereIn('print_profile_id', $printProfileIds)
					->where('asset_type_id', $assetTypeArr['asset_type_id']);
			});
		}

		$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']) {
							$page = $valueSort['page_no'];
							$perpage = !empty($valueSort['per_page']) ? $valueSort['per_page'] : '';
						} elseif ($isAdmin) {
							$page = 1;
							$perpage = 10;
						} else {
							$page = $perpage = "";
						}
						$colorData = $this->_getColorData(
							$value['parent_id'],
							$value['xe_id'],
							$catName,
							$otherFilterData,
							$page,
							$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) {
						$page = 1;
						$perpage = 10;
					} else {
						$page = $perpage = "";
					}
					$colorData = $this->_getColorData(
						$value['parent_id'],
						$value['xe_id'],
						$catName,
						$otherFilterData,
						$page,
						$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 $subcatId        Subcat 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, $subcatId, $catName, $otherFilterData, $page, $perpage)
	{
		$colordata = [];

		$colorPaletteInit = new ColorPalette();
		$getColor = $colorPaletteInit->select([
			'xe_id',
			'name',
			'price',
			'value',
			'hex_value',
			'cloud_storage'
		])->where([
			['xe_id', '>', 0],
			['category_id', '=', $catId],
			['subcategory_id', '=', $subcatId]
		]);
		// 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', 'colorpalette') . 'thumb_' . $value->value;
						$colorValue = $this->getS3URL($color, $otherFilterData['store_id']);
					} else {
						$colorValue = path('read', 'colorpalette') . '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', 'colorpalette'),
				[150],
				'string'
			);

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

			if ($uploadFileExt == 'csv' && !empty($fileName)) {
				try {
					// function to save data from csv
					$colorLastInsertId = $this->_saveCSVData(
						$storeId,
						$catId,
						$subcatId,
						$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,
						$subcatId,
						$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', 'colorpalette') . "thumb_" . $fileName;
							$fileToUpload = path('abs', 'colorpalette') . $fileName;
							$this->uploadFileToS3("colorpalette", $thumbFile, $getStoreDetails['store_id']);
							$this->uploadFileToS3("colorpalette", $fileToUpload, $getStoreDetails['store_id']);
							$allPostPutVars['cloud_storage'] = 1;
						}
						$allPostPutVars['value'] = $fileName;
					}

					$color = new ColorPalette($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'] . ']';
		//Clear Color Cache
		$this->updateAssetCache($storeId, $colorLastInsertId, $allPostPutVars, 'colorpalette');

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

	/**
	 * Saving data from csv file
	 *
	 * @param $storeId  Store_Id
	 * @param $catId    Category_Id
	 * @param $subcatId Subcategory_Id
	 * @param $filePath csv file path
	 *
	 * @author debashrib@riaxe.com
	 * @date   06 Dec 2019
	 * @return last inserted id
	 */
	private function _saveCSVData($storeId, $catId, $subcatId, $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 ColorPalette();
					$checkColor = $colorInit->where([
						'category_id' => $catId,
						'subcategory_id' => $subcatId,
						'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,
							'subcategory_id' => $subcatId,
							'name' => $column[0],
							'hex_value' => $column[1],
							'price' => (isset($column[2]) && $column[2] != "")
								? $column[2] : 0,
							'value' => $value
						];


						// Save Color Data
						$color = new ColorPalette($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, $subcatId, $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', 'colorpalette');
		$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,
							'subcategory_id' => $subcatId,
							'name' => $column[0],
							'price' => (isset($column[1]) && $column[1] != "")
								? $column[1] : 0,
							'cloud_storage' => ($isS3Enabled ? 1 : 0),
							'value' => $patternImg
						];
						// Save Color Data
						$color = new ColorPalette($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 ColorPalette();
				$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', 'colorpalette'),
							[150],
							'string'
						);

						if ($getOldColor['cloud_storage'] == 1) {
							// delete old file from the cloud
							$file = path('abs', 'colorpalette') . $getOldColor['value'];
							$thumbnail = path('abs', 'colorpalette') . "thumb_" . $getOldColor['value'];
							$this->deleteS3File($file, $storeId);
							$this->deleteS3File($thumbnail, $storeId);
							// move new file to the cloud
							$thumbUpload = path('abs', 'colorpalette') . "thumb_" . $getUploadedFileName;
							$fileToUpload = path('abs', 'colorpalette') . $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', 'colorpalette'),
								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'] . ']';
					//Clear Color Cache
					$this->updateAssetCache($storeId, $colorId, $updateData, 'colorpalette');
					$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', '', '', 'colorpalette');
		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 ColorPalette();

				// 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', 'colorpalette') . $colorFile['value'];
							$thumbfile = path('abs', 'colorpalette') . "thumb_" . $colorFile['value'];
							$this->deleteS3File($fileName, $storeId);
							$this->deleteS3File($thumbfile, $storeId);
						} else {
							$this->deleteOldFile(
								"color_palettes",
								"value",
								['xe_id' => $colorFile['xe_id']],
								path('abs', 'colorpalette'),
								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();
				//Clear Color Cache
				$this->updateAssetCache($storeId, $getDeleteIdsToArray, [$categoryList['category_id']], 'colorpalette');
				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', '', '', 'colorpalette');
		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 ColorPalette();
					$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', 'colorpalette') . $colorFile['value'];
							$thumbfile = path('abs', 'colorpalette') . "thumb_" . $colorFile['value'];
							$this->deleteS3File($fileName, $storeId);
							$this->deleteS3File($thumbfile, $storeId);
						} else {
							$this->deleteOldFile(
								"color_palettes",
								"value",
								['xe_id' => $colorFile['xe_id']],
								path('abs', 'colorpalette'),
								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', '', '', 'colorpalette');

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