<?php

/**
 * Manage Cliparts
 *
 * PHP version 5.6
 *
 * @category  Clipart
 * @package   Eloquent
 * @author    Tanmaya Patra <tanmayap@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\Cliparts\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Cliparts\Models\Clipart;
use App\Modules\Cliparts\Models\ClipartCategory as Category;
use App\Modules\Cliparts\Models\ClipartCategoryRelation;
use App\Modules\PrintProfiles\Models as PrintProfileModels;
use App\Modules\Cliparts\Models\ClipartTag as Tag;
use App\Modules\Cliparts\Models\ClipartTagRelation;
use Illuminate\Database\Capsule\Manager as DB;
use App\Modules\Customers\Controllers\CustomerGroupController as CustomerGroup;
use App\Components\Models\CategoryDetails;
use App\Modules\PrintProfiles\Models\PrintProfileAssetsCategoryRel;

/**
 * Clipart Controller
 *
 * @category Class
 * @package  Clipart
 * @author   Tanmaya Patra <tanmayap@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */

class ClipartController extends ParentController
{
	/**
	 * POST: Save Clipart
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author tanmayap@riaxe.com
	 * @date   12 Aug 2019
	 * @return json
	 * 
	 * @modifiedby dan@imprintnext.com
	 * @date   23 Jul 2022
	 */
	public function saveCliparts($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 0, 'message' => message('Cliparts', 'error')];
		try {
			$allPostPutVars = $request->getParsedBody();
			$categoryIds = isset($allPostPutVars['categories']) && $allPostPutVars['categories'] != "" ? $allPostPutVars['categories'] : NULL;
			$tags = !empty($allPostPutVars['tags'])	? $allPostPutVars['tags'] : "";
			$getStoreDetails = get_store_details($request);
			$success = 0;
			$isMultiUpload = false;
			$allUploadFileNames = $_FILES['upload']['name'];
			if (count($allUploadFileNames) > 1) {
				$isMultiUpload = true;
			}

			// Upload multiple Files
			$allFileNames = do_upload('upload', path('abs', 'vector'), [100], 'array');
			if (empty($allFileNames)) { # do not continue if files are not uploaded
				throw new \Exception('Cliart file upload error');
			}
			if (is_string($allFileNames) && $allFileNames == "limit_error") {
				$jsonResponse = [
					'status' => 1,
					'message' => "The upload limit is exceeded"
				];
			} else {
				$allFileNames = array_filter($allFileNames); # to removed empty vlues from array

				$isS3Enabled = $this->checkS3Settings($getStoreDetails['store_id']); # check S3
				$cloudStorage =  ($isS3Enabled ? 1 : 0);

				foreach ($allFileNames as $efk => $eachFile) {
					$name = "";
					if($isMultiUpload)
						$name = pathinfo($allUploadFileNames[$efk], PATHINFO_FILENAME);
					else
						$name = $allPostPutVars['name'];

					// Upload clipart to S3
					if ($cloudStorage) {
						$fileToUpload = path('abs', 'vector') . $eachFile;
						$this->uploadFileToS3("vector", $fileToUpload, $getStoreDetails['store_id']);
					}
					// clipart data
					$saveClipartList = [
						'store_id' => $getStoreDetails['store_id'],
						'name' => $name,
						'price' => $allPostPutVars['price'],
						'width' => $allPostPutVars['width'],
						'height' => $allPostPutVars['height'],
						'file_name' => $eachFile,
						'is_scaling' => $allPostPutVars['is_scaling'],
						'cloud_storage' => $cloudStorage
					];
					$saveEachClipart = new Clipart($saveClipartList);

					if ($saveEachClipart->save()) {
						$clipartId = $saveEachClipart->xe_id;
						/**
						 * Save category and subcategory data
						 * Category id format: [4,78,3]
						 */
						if ($categoryIds) {
							$this->saveClipartCategories($clipartId, $categoryIds);
						}
						/**
						 * Save tags with respect to the cliparts
						 * Tag Names format : tag1,tag2,tag3
						 */
						$this->saveClipartTags(
							$getStoreDetails['store_id'],
							$clipartId,
							$tags
						);
						$success++;
						//Clear Clipart Cache
						$this->updateAssetCache($getStoreDetails['store_id'], $clipartId, $allPostPutVars, 'clipart');
					}
					$this->memcache('deleteMulti', '', '', "cliparts_cat");
					if (!empty($categoryIds)) {
						$catgories = str_replace(array('\'', '"', '[', ']', '<', '>'), ' ', $categoryIds);
						$catIdArr = array_map('trim', array_filter(explode(",", $catgories)));
						foreach ($catIdArr as $categoryId) {
							$ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
							$printProfileIds = $ppAssetCatRelGtInit->where('category_id', $categoryId)->pluck('print_profile_id');
							$this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, 'cliparts', $request, $response);
						}
					}
				}
				if ($success) {
					$jsonResponse = ['status' => 1,	'message' => message('Clipart', 'saved')];
				}
			}
		} catch (\Exception $e) {
			$jsonResponse['message'] = $e->getMessage();
		}
		//Flush cliparts memcached
		$this->memcache('deleteMulti', '', '', 'clipart');
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * Get single clipart (Internal method)
	 *
	 * @param $request  Slim's Request object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author dan@imprintnext.com
	 * @date   22 Jul 2022
	 * @return json
	 * 
	 */

	private function _getSingleClipart($request, $args)
	{

		$jsonResponse = ['status' => 1, 'data' => [], 'message' => message('Clipart', 'not_found')];

		// Get Store Specific Details from helper
		$storeId = $request->getQueryParam('store_id');
		if (empty($storeId)) {
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];
		}

		$clipartInit = new Clipart();
		$getCliparts = $clipartInit->where('xe_id', '>', 0)->where('store_id', '=', $storeId);

		$clipartId = to_int($args['id']);

		// get the clipart
		$getCliparts->where('xe_id', $clipartId)
			->select('xe_id', 'name', 'price', 'width', 'height', 'file_name', 'is_scaling', 'is_imported', 'store_id', 'cloud_storage');

		if ($getCliparts->count() > 0) {

			$getClipart = $getCliparts->first()->toArray();
			if ($getClipart['cloud_storage'] == 1) {
				$fileName =  $this->getS3URL($getClipart['file_name'], $storeId);
				$thumbFile = $this->getS3URL($getClipart['thumbnail'], $storeId);
				$getClipart['file_name'] = $fileName;
				$getClipart['thumbnail'] = $thumbFile;
			}

			// get the categories of the clipart
			$getClipart['categories'] = $this->getCategoriesById('Cliparts', 'ClipartCategoryRelation', 'clipart_id', $clipartId);

			// get the tags of the clipart
			$getClipart['tags'] = $this->getTagsById('Cliparts', 'ClipartTagRelation', 'clipart_id', $clipartId);

			// Unset category_name Key in case of single record fetch
			unset($getClipart['category_names']);

			$jsonResponse = ['status' => 1, 'records' => 1, 'data' => [$getClipart]];
		}

		return $jsonResponse;
	}

	/**
	 * Get clipart for the tool (Internal method)
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object 
	 * @param $args     Slim's Argument parameters
	 *
	 * @author dan@imprintnext.com
	 * @date   22 Jul 2022
	 * @return json
	 * 
	 */
	private function _getClipartForTool($request, $response, $args)
	{
		$jsonResponse = [
			'status' => 1,
			'data' => [],
			'message' => message('Clipart', 'not_found')
		];
		// filter parameters
		$customerId = $request->getQueryParam('customer') ? $request->getQueryParam('customer') : '';
		$catPage = $request->getQueryParam('cat_page');
		$catPerpage = $request->getQueryParam('cat_perpage');
		$catOrder = (!empty($request->getQueryParam('cat_order')) && $request->getQueryParam('cat_order') != null) ? $request->getQueryParam('cat_order') : 'desc';
		$page = $request->getQueryParam('page');
		$perpage = $request->getQueryParam('perpage');
		$sortBy = (!empty($request->getQueryParam('sortby')) ? $request->getQueryParam('sortby') : 'xe_id');
		$order = (!empty($request->getQueryParam('order')) ? $request->getQueryParam('order') : 'desc');
		$source = $request->getQueryParam('source') ? $request->getQueryParam('source') : '';

		// Get store from the helper if not provided
		$storeId = $request->getQueryParam('store_id');
		if (empty($storeId)) {
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];
		}
		$currentStoreUrl = '';
		if ($storeId > 1) {
			$databaseStoreInfo = DB::table('stores')->where('xe_id', '=', $storeId);
			if ($databaseStoreInfo->count() > 0) {
				$currentStoreUrl = $databaseStoreInfo->get()->first()->store_url;
			}
		}
		// default fields
		$fields = ['xe_id', 'name', 'height', 'width', 'price', 'file_name', 'is_scaling', 'is_imported', 'cloud_storage'];
		$totalRecords = 0;
		$categoriesList = []; // returned category data - default blank
		$catIds = []; //customer group
		if (isset($customerId) && $customerId != '' && STORE_NAME != 'Opencart') {
			$customerGroupInit = new CustomerGroup();
			$customerGroupId = $customerGroupInit->getGroupIdBycustomerId($customerId, $storeId);
			if ($customerGroupId != '') {
				$assetTypeArr = $this->assetsTypeId('cliparts');
				$assetTypeId = $assetTypeArr['asset_type_id'];
				$catIds = $customerGroupInit->getAssetsBygroupId($customerGroupId, $assetTypeId, $storeId);
			}
		}

		// get the categories matching with category_ids
		if (!empty($catIds)) {
			$categoryInit = new Category();
			$getCategoryByIds = $categoryInit->whereIn('xe_id', $catIds)
			->select(['xe_id AS id', 'name', 'sort_order AS order', 'is_disable', 'is_default','file_name']);

			$totalRecords = $getCategoryByIds->count();
			// Pagination Category Data
			if (!empty($catPage)) {
				$totalItem = empty($catPerpage) ? PAGINATION_MAX_ROW : $catPerpage;
				$catOffset = $totalItem * ($catPage - 1);
				$getCategoryByIds->skip($catOffset)->take($totalItem);
			}
			// Sorting All records by column name and sord catOrder parameter
			if (!empty($sortBy) && !empty($catOrder)) {
				$getCategoryByIds->orderBy($sortBy, $catOrder);
			}
			// get all category : array format
			$categories = $getCategoryByIds->get()->toArray();
			$ind = -1; // used to unset the category for which no clipart present

			// go through the category and add corresponding clipart with pagination
			foreach ($categories as $catval) {
				++$ind;
				$clipartInit = new Clipart();
				// set conditions
				$getCliparts = $clipartInit->select($fields)->where('xe_id', '>', 0)->where(['store_id' => $storeId]);
				// match with category id
				$getCliparts->whereHas('clipartCategory', function ($q) use ($catval) {
					return $q->where('category_id', $catval['id']);
				});
				// unset the category for which no clipart present
				$getTotalPerFilters = $getCliparts->count();
				if ($getTotalPerFilters == 0) {
					unset($categories[$ind]);
					continue;
				}
				// Pagination Data
				if (!empty($page)) {
					$totalItem = empty($perpage) ? PAGINATION_MAX_ROW : $perpage;
					$offset = $totalItem * ($page - 1);
					$getCliparts->skip($offset)->take($totalItem);
				}
				// Sorting All records by column name and sord order parameter
				if (!empty($sortBy) && !empty($order)) {
					$getCliparts->orderBy($sortBy, $order);
				}

				$cliparts = [];
				if ($getCliparts->count() > 0) {
					$cliparts = $getCliparts->get()->toArray();
					foreach ($cliparts as &$value) {
						if ($value['cloud_storage'] == 1) {
							$fileName =  $this->getS3URL($value['file_name'], $storeId);
							$value['file_name'] = $value['thumbnail'] = $fileName;
							continue;
						}
						if (!$value['is_imported'] && IS_HOSTED == 0 && !empty($currentStoreUrl)) {
							$hostname = parse_url($value['file_name'], PHP_URL_HOST); // hostname
							$value['file_name'] = str_replace($hostname, $currentStoreUrl, $value['file_name']);
							$value['thumbnail'] = str_replace($hostname, $currentStoreUrl, $value['thumbnail']);
						}
					}
					unset($value);
				}
				$categoriesList[] = [
					'cliparts' => $cliparts,
					'records' =>  count($cliparts),
					'total_records' => $getTotalPerFilters,
					'id' => $catval['id'],
					'name' => $catval['name'],
					'image_path' => !empty($catval['file_name']) ? ASSETS_PATH_R . 'categories/' . 'thumb_' . $catval['file_name'] : '',
					'order' => $catval['order'],
					'is_disable' => $catval['is_disable'],
					'is_default' => $catval['is_default'],
					'description' => $catval['description'],
					'no_of_colors' => $catval['no_of_colors'],
					'print_profiles_match' => $catval['print_profiles_match'],
				];
			}
		} else {
			$clipartCategoryList = $this->getCategoryByPrintProfileId($request, $response, $args);
			if (!empty($clipartCategoryList) && !empty($clipartCategoryList['data'])) {
				$totalRecords = $clipartCategoryList['total_records'];
				foreach ($clipartCategoryList['data'] as $category) {
					if (empty($category['id'])) {
						continue;
					}
					// Filter by Category IDs and It's Subcategory IDs
					$clipartInit = new Clipart();
					$getCliparts = $clipartInit->select($fields)->where('xe_id', '>', 0)->where(['store_id' => $storeId]);

					// filter cliparts with matching category_id
					$getCliparts->whereHas('clipartCategory', function ($q) use ($category) {
						return $q->where('category_id', $category['id']);
					});

					$getTotalPerFilters = $getCliparts->count();

					// Pagination Data
					if (!empty($page)) {
						$totalItem = empty($perpage) ? PAGINATION_MAX_ROW : $perpage;
						$offset = $totalItem * ($page - 1);
						$getCliparts->skip($offset)->take($totalItem);
					}

					// Sorting All records by column name and sord order parameter
					if (!empty($sortBy) && !empty($order)) {
						$getCliparts->orderBy($sortBy, $order);
					}

					// get clipart in array format
					$cliparts = $getCliparts->get()->toArray();
					if (!empty($cliparts) && $source != 'admin') {
						foreach ($cliparts as &$value) {
							if ($value['cloud_storage'] == 1) {
								$fileName =  $this->getS3URL($value['file_name'], $storeId);
								$value['file_name'] = $value['thumbnail'] = $fileName;
								continue;
							}
							if (!$value['is_imported'] && IS_HOSTED == 0 && !empty($currentStoreUrl)) {
								$hostname = parse_url($value['file_name'], PHP_URL_HOST); //hostname
								$value['file_name'] = str_replace($hostname, $currentStoreUrl, $value['file_name']);
								$value['thumbnail'] = str_replace($hostname, $currentStoreUrl, $value['thumbnail']);
							}
						}
						unset($value);
					}

					$categoriesList[] = [
						'id' => $category['id'],
						'name' => $category['name'],
						'image_path' => !empty($category['file_name']) ? ASSETS_PATH_R . 'categories/' . 'thumb_' . $category['file_name'] : '',
						'order' => $category['order'],
						'is_disable' => $category['is_disable'],
						'is_default' => $category['is_default'],
						'description' => $category['description'],
						'no_of_colors' => $category['no_of_colors'],
						'print_profiles_match' => $category['print_profiles_match'],
						'cliparts' => $cliparts,
						'records' => count($cliparts),
						'total_records' => $getTotalPerFilters
					];
				}
			}
		}

		if (!empty($categoriesList)) {
			$jsonResponse = [
				'status' => 1,
				'records' => count($categoriesList),
				'total_records' => $totalRecords,
				'data' => $categoriesList,
			];
		}

		return $jsonResponse;
	}
	/**
	 * GET: List of Clipart
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author tanmayap@riaxe.com
	 * @date   13 Aug 2019
	 * @return json
	 * 
	 * @modifiedby dan@imprintnext.com
	 * @date   22 Jul 2022
	 */
	public function getCliparts($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'data' => [],
			'message' => message('Clipart', 'not_found')
		];

		// to get single clip art
		if (!empty($args['id'])) {
			$jsonResponse = $this->_getSingleClipart($request, $args);
			return response($response, [
				'data' => $jsonResponse, 'status' => $serverStatusCode
			]);
		}

		// Get the store ID from the helper if not provided in the request
		$currentStoreId = $storeId = $request->getQueryParam('store_id');
		if (empty($storeId)) {
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];
		}

		//All Filter columns from url
		$categoryId = $request->getQueryParam('category');
		if (!empty($categoryId)) {
			$categoryId = json_clean_decode($categoryId, true);
		}
		$page = $request->getQueryParam('page');
		$perpage = $request->getQueryParam('perpage');
		$catPage = $request->getQueryParam('cat_page');
		$catPerpage = $request->getQueryParam('cat_perpage');

		$sortBy = (!empty($request->getQueryParam('sortby')) ? $request->getQueryParam('sortby') : 'xe_id');
		$order = (!empty($request->getQueryParam('order')) ? $request->getQueryParam('order') : 'desc');
		$name = $request->getQueryParam('name');
		$printProfileKey = $request->getQueryParam('print_profile_id');
		$type = (string) $request->getQueryParam('type', '');
		$customerId = $request->getQueryParam('customer') ? $request->getQueryParam('customer') : 0;

		if ($type == 'tool') {
			$assetCacheData = [];
			$memcacheData = [];
			if (!empty($printProfileKey) && $catPage <= 2 && $name == '' && $customerId == 0) {
				$assetCacheData = $this->getAssetCache($currentStoreId, $printProfileKey, $catPage, $catPerpage, 'clipart');
			}

			if (IS_MEMCACHE and empty($name) and !empty($printProfileKey)) {
				//MEMCACHED KEY
				$thisCacheKey = "clipart" . "_page" . $page . "_order" . $order . "_perpage" . $perpage . "_pp" . $printProfileKey . "_s" . $storeId;

				//Register MEMCACHED KEY in Local Cache
				$this->createUpdateMemCacheGroup('clipart', $thisCacheKey, 'SET');

				//GET MEMCACHEDATA
				$memcacheData = $this->memcache("get", $thisCacheKey);
			}

			if (empty($memcacheData)) {
				if (empty($assetCacheData)) {
					$jsonResponse =  $this->_getClipartForTool($request, $response, $args);
					if (isset($printProfileKey) && !empty($printProfileKey) && $catPage <= 2 && $customerId == 0) {
						$assetData = $catPage == 1 ?
							[
								'total_records' => $jsonResponse['total_records'],
								'data' => $jsonResponse['data']
							] : $jsonResponse['data'];

						// creating cache folder in print-profile asset directory
						$this->createAssetCache('clipart', $currentStoreId, $printProfileKey, $assetData, $catPage);
					}
				} else {
					$jsonResponse = [
						'status' => 1,
						'total_records' => $assetCacheData['total_records'],
						'records' => count($assetCacheData['data']),
						'data' => $assetCacheData['data']
					];
				}
				if (IS_MEMCACHE and empty($name) && $customerId == 0) {
					$this->memcache("set", $thisCacheKey, $jsonResponse);
				}
			} else {
				$jsonResponse = $memcacheData;
				if (MEM_MODE) {
					$jsonResponse['mode'] = 'memcache';
				}
			}
			if (!empty($assetCacheData)) {
				$jsonResponse = [
					'status' => 1,
					'total_records' => $assetCacheData['total_records'],
					'records' => count($assetCacheData['data']),
					'data' => $assetCacheData['data']
				];
			}
			return response($response, [
				'data' => $jsonResponse, 'status' => $serverStatusCode
			]);
		}

		$fields = ['xe_id', 'name', 'height', 'width', 'price', 'file_name', 'is_scaling', 'is_imported', 'cloud_storage'];

		$clipartInit = new Clipart();
		$getCliparts = $clipartInit->where('xe_id', '>', 0)->where('store_id', '=', $storeId);
		$getCliparts->select($fields);

		// Searching as per clipart name, category name & tag name
		if (isset($name) && $name != "") {
			$name = '\\' . $name;
			$getCliparts->where(
				function ($query) use ($name) {
					$query->where('name', 'LIKE', '%' . $name . '%')
						->orWhereHas(
							'clipartTags.tag',
							function ($q) use ($name) {
								return $q->where('name', 'LIKE', '%' . $name . '%');
							}
						)->orWhereHas(
							'clipartCategory.category',
							function ($q) use ($name) {
								return $q->where('name', 'LIKE', '%' . $name . '%');
							}
						);
				}
			);
		}
		// Filter By Print Profile's asset-category id
		if (!empty($printProfileKey)) {
			$assetTypeArr = $this->assetsTypeId('cliparts');
			$profileCatRelObj = new \App\Modules\PrintProfiles\Models\PrintProfileAssetsCategoryRel();
			// get the asset's category from print profile
			$categoryId = $profileCatRelObj->where('asset_type_id', $assetTypeArr['asset_type_id'])
				->where('print_profile_id', $printProfileKey)
				->pluck('category_id')->toArray();
		}
		// if category_id found, add as filter to the query	
		if (!empty($categoryId)) {
			$getCliparts->whereHas('clipartCategory', function ($q) use ($categoryId) {
				return $q->whereIn('category_id', $categoryId);
			});
		}
		// Total records including all filters
		$getTotalPerFilters = $getCliparts->count();

		// Pagination Data
		if (!empty($page)) {
			$totalItem = empty($perpage) ? PAGINATION_MAX_ROW : $perpage;
			$offset = $totalItem * ($page - 1);
			$getCliparts->skip($offset)->take($totalItem);
		}
		// Sorting All records by column name and sord order parameter
		if (!empty($sortBy) && !empty($order)) {
			$getCliparts->orderBy($sortBy, $order);
		}
		if ($getTotalPerFilters > 0) {
			$currentStoreUrl = '';
			if ($storeId > 1) {
				$databaseStoreInfo = DB::table('stores')->where('xe_id', '=', $storeId)->get()->first();
				if (!empty($databaseStoreInfo)) {
					$currentStoreUrl = $databaseStoreInfo->store_url;
				}
			}

			$cliparts = $getCliparts->get()->toArray();
			foreach ($cliparts as &$value) {
				if ($value['cloud_storage'] == 1) {
					$fileName =  $this->getS3URL($value['file_name'], $storeId);
					$value['file_name'] = $value['thumbnail'] = $fileName;
				} else {
					if ($value['is_imported'] == 0 && IS_HOSTED == 0 && !empty($currentStoreUrl)) {
						$file_name = $value['file_name'];
						$thumbnail = $value['thumbnail'];
						$hostname = parse_url($file_name, PHP_URL_HOST); //hostname
						$value['file_name'] = str_replace($hostname, $currentStoreUrl, $file_name);
						$value['thumbnail'] = str_replace($hostname, $currentStoreUrl, $thumbnail);
					}
				}
			}
			$jsonResponse = [
				'status' => 1,
				'records' => count($cliparts),
				'total_records' => $getTotalPerFilters,
				'data' => $cliparts // Convert object to Array
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
	/**
	 * PUT: Update a single clipart
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author tanmayap@riaxe.com
	 * @date   13 Aug 2019
	 * @return json
	 */
	public function updateClipart($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 0, 'message' => message('Clipart', 'error')];
		try {
			// Get Store Specific Details from helper
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];
			$allPostPutVars = $updateData = $request->getParsedBody();
			$categoryIds = (isset($allPostPutVars['categories']) && $allPostPutVars['categories'] != "") ?
				$allPostPutVars['categories'] : NULL;
			$tags = !empty($allPostPutVars['tags']) ? $allPostPutVars['tags'] : "";
			$clipartId = to_int($args['id']);

			if ($clipartId) {
				$clipartInit = new Clipart();
				$findClipArt = $clipartInit->where('xe_id', $clipartId);
				if (!$findClipArt->count()) {
					throw new \Exception('Clipart not found');
				}
				$getOldClipart = $findClipArt->first()->toArray();
				$oldCategoryArr = explode(",", $getOldClipart['category_id']);
				$newCategory = str_replace(array('\'', '"', '[', ']', '<', '>'), ' ', $categoryIds);
				$newCategoryArr = explode(",", $newCategory);
				$result = array_diff($oldCategoryArr, $newCategoryArr);
				foreach ($result as $res) {
					$clipartCount = new ClipartCategoryRelation();
					$countData = $clipartCount->where('category_id', '=', $res)->get()->toArray();
					$clipartCat = new Category();
					if (count($countData) == 1) {
						$flagList = ['asset_available_flag' => 0];
						$clipartCat->where('xe_id', '=', $res)->update($flagList);
					} else {
						$flagList = ['asset_available_flag' => 1];
						$clipartCat->where('xe_id', '=', $res)->update($flagList);
					}
				}
				$updateData = [
					'store_id' => $storeId,
					'name' => $allPostPutVars['name'],
					'price' => $allPostPutVars['price'],
					'width' => $allPostPutVars['width'],
					'height' => $allPostPutVars['height'],
					'is_scaling' => $allPostPutVars['is_scaling']
				];

				// if file is received replace the file on the server + cloud
				if ($request->getUploadedFiles()) {
					// delete old file from the server
					$this->deleteOldFile('cliparts', 'file_name', ['xe_id' => $clipartId], path('abs', 'vector'));
					// upload new file to the server
					$getUploadedFileName = do_upload('upload', path('abs', 'vector'), [100], 'string');
					if (!empty($getUploadedFileName)) {
						$updateData['file_name'] = $getUploadedFileName;
						$updateData['is_imported'] = '0';
					}

					if ($getOldClipart['cloud_storage'] == 1) {
						if ($getOldClipart['cloud_storage']) {
							$this->deleteS3File($getOldClipart['file_name'], $storeId); // delete old file from cloud
						}
						$updateData['cloud_storage'] = 1;
						// upload new file to the cloud
						$fileToUpload = path('abs', 'vector') . $getUploadedFileName;
						$this->uploadFileToS3("vector", $fileToUpload, $storeId);
					}
				}

				// Update record into the database
				$clipartInit = new Clipart();
				$clipartInit->where('xe_id', '=', $clipartId)->update($updateData);
				//Clear Clipart cache
				$this->updateAssetCache($storeId, $clipartId, $allPostPutVars, 'clipart');
				$jsonResponse = ['status' => 1, 'message' => message('Clipart', 'updated')];

				/**
				 * Save category and subcategory data
				 * Category id format: [4,78,3]
				 */
				if ($categoryIds) {
					$this->saveClipartCategories($clipartId, $categoryIds);
				}
				/**
				 * Save tags with respect to the cliparts
				 * Tag Names format : tag1,tag2,tag3
				 */
				$this->saveClipartTags($getStoreDetails['store_id'], $clipartId, $tags);
				$this->memcache('deleteMulti', '', '', "cliparts_cat");
				if (!empty($categoryIds)) {
					$catgories = str_replace(array('\'', '"', '[', ']', '<', '>'), ' ', $categoryIds);
					$catIdArr = array_map('trim', array_filter(explode(",", $catgories)));
					foreach ($catIdArr as $categoryId) {
						$ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
						$printProfileIds = $ppAssetCatRelGtInit->where('category_id', $categoryId)->pluck('print_profile_id');
						$this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, 'cliparts', $request, $response);
					}
				}
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			create_log('clipart', 'error', [
				'message' => $e->getMessage(),
				'extra' => ['module' => 'Updating a clipart']
			]);
		}

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

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

	/**
	 * Delete: Delete a clipart along with all the tags and categories
	 *
	 * @param $request  Slim's Argument parameters
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author tanmayap@riaxe.com
	 * @date   13 Aug 2019
	 * @return json
	 */
	public function deleteClipart($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 0, 'message' => message('Clipart', 'error')];
		if (!empty($args['id'])) {
			try {
				$getStoreDetails = get_store_details($request);
				// Multiple Ids in json format
				$getDeleteIdsToArray = json_clean_decode(trim($args['id']), true);
				if (!empty($getDeleteIdsToArray)) {

					$clipartInit = new Clipart();
					$getCliparts  = $clipartInit->whereIn('xe_id', $getDeleteIdsToArray);

					$clipartCount = $getCliparts->count();
					if (!$clipartCount) {
						throw new \Exception('Clipart not found'); # error when no clipart found
					}

					$success = 0;
					$getCliparts  = $getCliparts->select('*')->get()->toArray();
					foreach ($getCliparts as $clipart) {
						$categoryIdArr = explode(",", $clipart['category_id']);
						foreach ($categoryIdArr as $catId) {
							$clipartCount = new ClipartCategoryRelation();
							$countData = $clipartCount->where('category_id', '=', $catId)->get()->toArray();
							$clipartCat = new Category();
							if (count($countData) == 1) {
								$flagList = ['asset_available_flag' => 0];
								$clipartCat->where('xe_id', '=', $catId)->update($flagList);
							} else {
								$flagList = ['asset_available_flag' => 1];
								$clipartCat->where('xe_id', '=', $catId)->update($flagList);
							}
						}
						// delete file from cloud if enabled
						if ($clipart['cloud_storage'] == 1) {
							$this->deleteS3File($clipart['file_name'], $getStoreDetails['store_id']);
						}
						// delete file from the server
						$this->deleteOldFile('cliparts', 'file_name', ['xe_id' => $clipart['xe_id']], path('abs', 'vector'), false);
						$clipartCount->where('clipart_id', $clipart['xe_id'])->delete();
						// delete the record
						$clipartInit->where('xe_id', $clipart['xe_id'])->delete();
						$success++;
					}

					$requestData = $this->updateAssetCache($getStoreDetails['store_id'], $getDeleteIdsToArray, $categoryIdArr, 'clipart');

					if (!empty($requestData)) {
						foreach ($requestData['print_profile'] as $printProfileId) {
							$params = [
								'print_profile_id' =>  $printProfileId,
								'cat_page' => $requestData['page'],
								'cat_perpage' => $requestData['perpage'],
								'type' => 'tool',
								'store_id' => $getStoreDetails['store_id'],
							];
							$request = $request->withQueryParams($params);
							$this->getCliparts($request, $response, []);
						}
					}
					$this->memcache('deleteMulti', '', '', "cliparts_cat");
					if (!empty($categoryIdArr)) {
						foreach ($categoryIdArr as $categoryId) {
							$ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
							$printProfileIds = $ppAssetCatRelGtInit->where('category_id', $categoryId)->pluck('print_profile_id');
							$this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, 'cliparts', $request, $response);
						}
					}
					if ($success) {
						$totalCount = count($getDeleteIdsToArray);
						$jsonResponse = [
							'status' => 1,
							'message' => $success . ' out of ' . $totalCount . ' Clipart(s) deleted successfully',
						];
					}
				}
			} catch (\Exception $e) {
				$serverStatusCode = EXCEPTION_OCCURED;
				create_log('clipart', 'error', [
					'message' => $e->getMessage(),
					'extra' => ['module' => 'Deleting a clipart']
				]);
			}
		}

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

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

	/**
	 * Save Tags and Clipart-Tag Relations
	 *
	 * @param $storeId   Store Id
	 * @param $clipartId Clipart's ID
	 * @param $tags      Tags(in comma separated)
	 *
	 * @author tanmayap@riaxe.com
	 * @date   13 Aug 2019
	 * @return boolean
	 */
	public function saveClipartTags($storeId, $clipartId, $tags)
	{
		// Save Clipart and tags relation
		if (!empty($tags)) {
			$getTagIds = $this->saveTags($storeId, $tags);
			// SYNC Tags into Clipart Tag Relationship Table
			$clipartInit = new Clipart();
			$findClipart = $clipartInit->find($clipartId);
			if ($findClipart->tags()->sync($getTagIds)) {
				return true;
			}
		} else {
			// Clean relation in case no tags supplied
			$tagRelInit = new ClipartTagRelation();
			$clipartTags = $tagRelInit->where('clipart_id', $clipartId);
			if ($clipartTags->delete()) {
				return true;
			}
		}

		return false;
	}

	/**
	 * Save Categories/Sub-categories and Clipart-Category Relations
	 *
	 * @param $clipartId   Clipart's ID
	 * @param $categoryIds (in comma separated)
	 *
	 * @author tanmayap@riaxe.com
	 * @date   13 Aug 2019
	 * @return boolean
	 */
	public function saveClipartCategories($clipartId, $categoryIds)
	{
		$getAllCategoryArr = json_clean_decode($categoryIds, true);
		foreach ($getAllCategoryArr as $catId) {
			$clipartCat = new Category();
			$categoriesData = $clipartCat->where('xe_id', '=', $catId)->get()->toArray();
			if ($catId == $categoriesData[0]['xe_id']) {
				$flagList = ['asset_available_flag' => 1];
				$clipartCat->where('xe_id', '=', $catId)->update($flagList);
			}
			$clipartCount = new ClipartCategoryRelation();
			$countData = $clipartCount->where('category_id', '=', $catId)->get();
			$countDataArr = $countData->toArray();
			if (count($countData) == 0) {
				if ($catId == $countDataArr[0]['category_id']) {
					$flagList = ['asset_available_flag' => 0];
					$clipartCat->where('xe_id', '=', $catId)->update($flagList);
				}
			} else {
				if ($catId == $countDataArr[0]['category_id']) {
					$flagList = ['asset_available_flag' => 1];
					$clipartCat->where('xe_id', '=', $catId)->update($flagList);
				}
			}
		}
		// SYNC Categories to the Clipart_Category Relationship Table
		$clipartInit = new Clipart();
		$findClipart = $clipartInit->find($clipartId);
		if ($findClipart->categories()->sync($getAllCategoryArr)) {
			return true;
		}

		return false;
	}

	/**
	 * Delete a category from the table
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author satyabratap@riaxe.com
	 * @date   20 Jan 2020
	 * @return Delete Json Status
	 */
	public function deleteCategory($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 0, 'message' => message('Category', 'error')];
		try {
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];
			if (!empty($args)) {
				$categoryId = $args['id'];
				$jsonResponse = $this->deleteCat(
					$storeId,
					'cliparts',
					$categoryId,
					'Cliparts',
					'ClipartCategoryRelation'
				);
			}
			$this->memcache('deleteMulti', '', '', "cliparts_cat");
			if (!empty($args['id'])) {
				$ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
				$printProfileIds = $ppAssetCatRelGtInit->where('category_id', $args['id'])->pluck('print_profile_id');
				$this->createUpdateAssetJsonCache($getStoreDetails['store_id'], $printProfileIds, "cliparts", $request, $response);
			}
		} catch (\Exception $e) {
			$jsonResponse['message'] = $e->getMessage();
		}

		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
	/**
	 * Get most used cliparts
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author debashrib@riaxe.com
	 * @date   30 Jan 2020
	 * @return A json
	 */
	public function mostUsedCliparts($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 0, 'message' => message('Cliparts', 'error')];
		try {
			$getStoreDetails = get_store_details($request); // get the store details
			$page = $request->getQueryParam('page');
			$perpage = $request->getQueryParam('perpage');

			$clipartInit = new Clipart();
			// get the clipart with matching store
			$getCliparts = $clipartInit->where(['store_id' => $getStoreDetails['store_id']])
				->select('xe_id', 'name', 'file_name');

			$totalCounts = $getCliparts->count();
			if ($totalCounts > 0) {
				// Get pagination data
				if (!empty($page)) {
					$totalItem = empty($perpage) ? PAGINATION_MAX_ROW : $perpage;
					$offset = $totalItem * ($page - 1);
					$getCliparts->skip($offset)->take($totalItem);
				}
				// order the result to get the most-used cliparts first
				$clipartsData = $getCliparts->orderBy('total_used', 'DESC')->get();

				$jsonResponse = [
					'status' => 1,
					'total_records' => $totalCounts,
					'records' => count($clipartsData),
					'data' => $clipartsData,
				];
			}
		} catch (\Exception $e) {
			$response['message'] = $e->getMessage();
		}

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

	/**
	 * Get all Categories in Recursion format from the Database
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author radhanatham@riaxe.com
	 * @date   10 Spt 2020
	 * @return json
	 */
	private function getCategoryByPrintProfileId($request, $response, $args)
	{
		//All Filter columns from url
		$categoryId = $request->getQueryParam('category');
		$page = $request->getQueryParam('cat_page');
		$perpage = $request->getQueryParam('cat_perpage');
		$printProfileId = $request->getQueryParam('print_profile_id');
		$primaryCategory = (!empty($request->getQueryParam('primary_cat')) && $request->getQueryParam('primary_cat') != null
		) ? $request->getQueryParam('primary_cat') : 0;
		$name = $request->getQueryParam('name');

		// get the store details
		$getStoreDetails = get_store_details($request);
		$clipartsCategories = $primaryCategoryArr  = $clipartsCategoriesData = [];
		// get the asset type
		$assetTypeArr = $this->assetsTypeId('cliparts');


		if ($printProfileId > 0 && !empty($assetTypeArr) && $assetTypeArr['status'] == 1) {
			// Getting Assets module id
			$assetTypeId = $assetTypeArr['asset_type_id'];
			### primary category remains empty on api calls - need to check
			if (!empty($primaryCategory) && $page == 1) {
				$getPrimaryProfileCat = DB::table('print_profile_assets_category_rel as ppac')
					->leftjoin('clipart_category_rel as ccr', 'ppac.category_id', '=', 'ccr.category_id')
					->join('categories as cat', 'ppac.category_id', '=', 'cat.xe_id')
					->join('cliparts as c', 'ccr.clipart_id', '=', 'c.xe_id')
					->leftjoin('clipart_tag_rel as ct', 'c.xe_id', '=', 'ct.clipart_id')
					->leftjoin('tags as t', 'ct.tag_id', '=', 't.xe_id')
					->where('ppac.asset_type_id', $assetTypeId)
					->where('ppac.print_profile_id', $printProfileId)
					->where('ppac.category_id', $primaryCategory)
					->select('cat.xe_id as id', 'cat.parent_id', 'cat.name', 'cat.sort_order', 'cat.is_disable', 'cat.is_default')
					->distinct('cat.xe_id');
				if ($getPrimaryProfileCat->count() > 0) {
					$primaryProfileCat = $getPrimaryProfileCat->get()->first();
					$primaryCategoryArr = [
						'id' => $primaryProfileCat->id,
						'name' => $primaryProfileCat->name,
						'order' => $primaryProfileCat->sort_order,
						'is_disable' => $primaryProfileCat->is_disable,
						'is_default' => $primaryProfileCat->is_default
					];
				}
			}

			// categories based on print profile
			$profileCat = DB::table('print_profile_assets_category_rel as ppac')
				->leftjoin('clipart_category_rel as ccr', 'ppac.category_id', '=', 'ccr.category_id')
				->join('categories as cat', 'ppac.category_id', '=', 'cat.xe_id')
				->join('cliparts as c', 'ccr.clipart_id', '=', 'c.xe_id')
				->leftjoin('clipart_tag_rel as ct', 'c.xe_id', '=', 'ct.clipart_id')
				->leftjoin('tags as t', 'ct.tag_id', '=', 't.xe_id')
				->where('ppac.asset_type_id', $assetTypeId)
				->where('ppac.print_profile_id', $printProfileId)
				->where('c.store_id', $getStoreDetails['store_id'])
				->where('cat.store_id', $getStoreDetails['store_id']);

			// add more filters
			if (!empty($categoryId)) {
				$searchCategories = json_clean_decode($categoryId, true);
				if ($searchCategories != '') {
					$profileCat = $profileCat->whereIn('ppac.category_id', $searchCategories);
				}
			}
			if (isset($name) && $name != "") {
				$profileCat->where(function ($query) use ($name) {
					$query->where('c.name', 'LIKE', '%' . $name . '%')
						->orWhere('cat.name', 'LIKE', '%' . $name . '%')
						->orWhere('t.name', 'LIKE', '%' . $name . '%');
				});
			}
			$profileCat->select('cat.xe_id as id', 'cat.parent_id', 'cat.name', 'cat.file_name',  'cat.sort_order', 'cat.is_disable', 'cat.is_default')->distinct('cat.xe_id');

			$getTotalPerFilters = $profileCat->count(); // get the total category records

			// pagination part
			if (!empty($page)) {
				$totalItem = empty($perpage) ? PAGINATION_MAX_ROW : $perpage;
				$offset = $totalItem * ($page - 1);
				$profileCat->orderBy('sort_order', 'asc')->skip($offset)->take($totalItem);
			}

			if ($getTotalPerFilters > 0) {
				$profileCategory = $profileCat->get()->toArray();
				foreach ($profileCategory as $value) {
					$clipartsCategoriesData[] = [
						'id' => $value->id,
						'name' => $value->name,
						'file_name' => $value->file_name,
						'order' => $value->sort_order,
						'is_disable' => $value->is_disable,
						'is_default' => $value->is_default,
					];
				}
				$allClipartCategory = array_merge($primaryCategoryArr, $clipartsCategoriesData);
				$keys = array_column($allClipartCategory, 'order');
				array_multisort($keys, SORT_ASC, $allClipartCategory);
				$clipartsCategories = [
					'records' => count($profileCategory),
					'total_records' => $getTotalPerFilters,
					'data' => array_map("unserialize", array_unique(array_map("serialize", $allClipartCategory)))
				];
			}
		}
		return $clipartsCategories;
	}

	/**
	 * Get cliparts for listing from central server to import.
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soam@imprintnext.com
	 * @date   22 July 2021
	 * @return json
	 */

	public function importCliparts($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 0, 'message' => message('Cliparts', 'error')];
		try {
			$catIds = $request->getQueryParam("cat_id");
			// get clipart from the central server
			if (!empty($catIds)) {
				$endPoint = CENTRAL_ASSETS_BASEURL . "api/v1/cliparts-info";
				$jsonResponse = api_call_by_curl(["cat_id" => $catIds], $endPoint, false, false);
				if (!empty($jsonResponse['data'])) {
					foreach ($jsonResponse['data'] as $key => $cat) {
						$categoryInit = new Category();
						$result = $categoryInit->where('import_id', '=', $jsonResponse['data'][$key]['id'])->get();
						if ($result->count() > 0) {
							$jsonResponse['data'][$key]['is_imported'] = '1';
						} else {
							$jsonResponse['data'][$key]['is_imported'] = '0';
						}
					}
				}
				return response($response, [
					'data' => $jsonResponse, 'status' => $serverStatusCode
				]);
			}

			$catPage = $request->getQueryParam('cat_page');
			$catPerpage = $request->getQueryParam('cat_perpage');
			$catOrder = (!empty($request->getQueryParam('cat_order')) ? $request->getQueryParam('cat_order') : 'desc');
			$subCatAllow = (!empty($request->getQueryParam('sub_cat')) ? $request->getQueryParam('sub_cat') : 1);
			$searchKey = $request->getQueryParam('search_cat_name');

			$categoryInit = new Category();
			$getCategory = $categoryInit->where(['asset_type_id' => 2]); // default filter
			// apply filters
			if ($subCatAllow == "false") {
				$getCategory->where(['parent_id' => 0]);
			}
			if (!empty($searchKey)) {
				$getCategory->where('name', 'LIKE', '%' . $searchKey . '%');
			}

			$totalRecords = $getCategory->count(); // total records

			// Pagination Data
			if (!empty($catPage)) {
				$totalItem = empty($catPerpage) ? PAGINATION_MAX_ROW : $catPerpage;
				$catOffset = $totalItem * ($catPage - 1);
				$getCategory->skip($catOffset)->take($totalItem);
			}
			// Sorting All records by column name and sord catOrder parameter
			if (!empty($catOrder)) {
				$getCategory->orderBy($catOrder);
			}
			// get the result in array format
			$getCategoryArray = $getCategory->get()->toArray();

			if (!empty($getCategoryArray)) {
				$jsonResponse = [
					'status' => 1,
					'records' => count($getCategoryArray),
					'total_records' => $totalRecords,
					'data' => $getCategoryArray,
				];
			}
		} catch (\Exception $e) {
			$jsonResponse['message'] = $e->getMessage();
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * Import clipart from central server to client's server.
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soam@imprintnext.com
	 * @date   22 July 2021
	 * @return json
	 */
	public function saveimportCliparts($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 1, 'data' => [], 'message' => message('Clipart', 'not_found')];
		try {
			$allPostPutVars = $request->getParsedBody();
			$catIds = $allPostPutVars["cat_id"];
			$storeId = $allPostPutVars["store_id"] ? $allPostPutVars["store_id"] : 1;
			$categoryIds = (isset($allPostPutVars['categories']) && $allPostPutVars['categories'] != "") ?
				$allPostPutVars['categories'] : NULL;
			$insertData = [];

			// call to the central asset to get all cliparts based on the category
			$endPoint = CENTRAL_ASSETS_BASEURL . "api/v1/cliparts-info";
			$clipartData = api_call_by_curl(["cat_id" => $catIds], $endPoint, false, false);
			$cliparts = $clipartData['data'];

			if (!empty($cliparts)) {
				$clipartInit = new Clipart();
				foreach ($cliparts as $key => $subCat) {
					if (empty($subCat['cliparts'])) {
						continue;
					}
					$insertCliparts = $subCat['cliparts'];
					foreach ($insertCliparts as $insertkey => $iClipart) {
						if ($iClipart['is_imported'] != 0) {
							continue;
						}
						// delete the existing clipart if matches with the imported clipart
						$clipartInit->where(['file_name' => $iClipart['raw_file_name'], 'is_imported' => '1'])->delete();

						// create new clipart with improted data
						$insertData[$insertkey] = [
							'name' => $iClipart['name'],
							'price' => $iClipart['price'],
							'width' => $iClipart['width'],
							'height' => $iClipart['height'],
							'file_name' => $iClipart['raw_file_name'],
							'is_scaling' => $iClipart['is_scaling'],
							'total_used' => $iClipart['total_used'],
							'is_imported' => '1',
							'store_id' => $storeId,
						];
						$saveEachClipart = new Clipart($insertData[$insertkey]);

						if ($saveEachClipart->save()) {
							$clipartId = $saveEachClipart->xe_id;

							// find the category if exisiting
							// $categoryName = (empty($iClipart['category_names']) ? $subCat['name'] : $iClipart['category_names']);
							$categoryName = $cliparts[0]['name'] == $iClipart['category_names']	? $cliparts[0]['name'] : $subCat['name'];
							$categoryInit = new Category();
							$getCategoryByName = $categoryInit->where('asset_type_id', '=', 2)->where('name', '=', $categoryName);
							$importId = $cliparts[0]['name'] == $iClipart['category_names'] ? $cliparts[0]['id'] : $subCat['id'];
							if ($getCategoryByName->count() > 0) {
								$getCategory = $getCategoryByName->get()->first();
								$categoryId = $getCategory->xe_id; // get the category_id
								$categoryInit->where('xe_id', '=', $categoryId)->update(['import_id' => $importId]);
								// Delete old PrintProfile - AssetsCategory relation record
								$profileCatRelDel = new PrintProfileAssetsCategoryRel();
								$profileCatRelDel->where(['category_id' => $categoryId])->delete();
							} else {
								$insertCat = [
									"asset_type_id" => 2,
									"name" => $categoryName,
									"parent_id" => 0,
									"sort_order" => $cliparts[$key]['sort_order'],
									"store_id" => $storeId,
									"is_defined" => $cliparts[$key]['is_defined'],
									"import_id" => $importId
								];
								$categoryInit = new Category($insertCat);
								$categoryInit->save();
								$categoryId = $categoryInit->xe_id; // get the category_id
							}

							// add clipart-category relationship
							if (!empty($categoryIds)) {
								$catgories = str_replace(array('\'', '"', '[', ']', '<', '>'), ' ', $categoryIds);
								$catIdArr = array_map('trim', array_filter(explode(",", $catgories)));
								foreach ($catIdArr as $categoryId) {
									$clipartCategoryInit = new ClipartCategoryRelation();
									$relationData = ["clipart_id" => $clipartId, "category_id" => $categoryId];
									$clipartCategoryInit->insert($relationData);
									// create print profile relation
									if (!empty($allPostPutVars["print_id"])) {
										// Delete old PrintProfile - AssetsCategory relation record
										$profileCatRelDel = new PrintProfileAssetsCategoryRel();
										$profileCatRelDel->where(['category_id' => $categoryId])->delete();
										// End

										foreach ($allPostPutVars["print_id"] as $printMethodID) {
											$printProfileInit = new PrintProfileAssetsCategoryRel();
											$printProfileInit->print_profile_id = $printMethodID;
											$printProfileInit->category_id = $categoryId;
											$printProfileInit->asset_type_id = 2;
											$printProfileInit->save();
										}
									}
								}
							} else {
								$clipartCategoryInit = new ClipartCategoryRelation();
								$relationData = ["clipart_id" => $clipartId, "category_id" => $categoryId];
								$clipartCategoryInit->insert($relationData);
								// create print profile relation
								if (!empty($allPostPutVars["print_id"])) {
									foreach ($allPostPutVars["print_id"] as $printMethodID) {
										$printProfileInit = new PrintProfileAssetsCategoryRel();
										$printProfileInit->print_profile_id = $printMethodID;
										$printProfileInit->category_id = $categoryId;
										$printProfileInit->asset_type_id = 2;
										$printProfileInit->save();
									}
								}
							}

						}
					}
				}
			}
			$assetParams['categories'] = '[' . $categoryId . ']';
			//Clear Clipart Cache
			$this->updateAssetCache($storeId, $clipartId, $assetParams, 'clipart');
			$this->memcache('deleteMulti', '', '', "cliparts_cat");
			if (empty($categoryIds)) {
				$categoryIds = $assetParams['categories'];
			}
			if (!empty($categoryIds)) {
				$catgories = str_replace(array('\'', '"', '[', ']', '<', '>'), ' ', $categoryIds);
				$catIdArr = array_map('trim', array_filter(explode(",", $catgories)));
				foreach ($catIdArr as $categoryId) {
					$ppAssetCatRelGtInit = new PrintProfileModels\PrintProfileAssetsCategoryRel();
					$printProfileIds = $ppAssetCatRelGtInit->where('category_id', $categoryId)->pluck('print_profile_id');
					$this->createUpdateAssetJsonCache($storeId, $printProfileIds, 'cliparts', $request, $response);
				}
			}
			if (!empty($insertData)) {
				$jsonResponse = [
					'status' => 1,
					'total_records' => count($insertData),
					'data' => $insertData,
					'message' => message('Clipart', 'saved'),
				];
			}
		} catch (\Exception $e) {
			$jsonResponse['message'] = $e->getMessage();
		}

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

	/**
	 * fetch category from central server to client's server.
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soam@imprintnext.com
	 * @date   25 Aug 2021
	 * @return json
	 */

	public function fetchCategory($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 1, 'data' => [], 'message' => message('Category', 'not_found')];
		try {
			// fiter parameters
			$catPage = $request->getQueryParam('cat_page');
			$catPerpage = $request->getQueryParam('cat_perpage');
			$catOrder = (!empty($request->getQueryParam('cat_order')) && $request->getQueryParam('cat_order') != null) ?
				$request->getQueryParam('cat_order') : 'desc';
			$searchKey = $request->getQueryParam('search_cat_name');

			// get all categories from the api.
			$endPoint = CENTRAL_ASSETS_BASEURL . "api/v1/cliparts-info";
			$allCategory = api_call_by_curl([
				"cat_page" => $catPage,
				"cat_perpage" => $catPerpage,
				"cat_order" => $catOrder,
				"sub_cat" => "false",
				"search_cat_name" => $searchKey
			], $endPoint, false, false);

			// all category from the API
			$allCategoryArray = $allCategory['data'];

			if (!empty($allCategoryArray)) {
				foreach ($allCategoryArray as $key => $cat) {
					$categoryInit = new Category();
					$result = $categoryInit->where('import_id', '=', $allCategoryArray[$key]['xe_id'])->get();
					$allCategoryArray[$key]['id'] = $allCategoryArray[$key]['xe_id'];
					if ($result->count() > 0) {
						$allCategoryArray[$key]['is_imported'] = '1';
					} else {
						$allCategoryArray[$key]['is_imported'] = '0';
					}
				}
			}


			if (!empty($allCategoryArray)) {
				$jsonResponse = [
					'status' => 1,
					'records' =>  count($allCategoryArray),
					'total_records' => $allCategory['total_records'],
					'data' => $allCategoryArray
				];
			}
		} catch (\Exception $e) {
			$response['message'] = $e->getMessage();
		}

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


	/**
	 * fetch cliparts with categories from central server to client's server.
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author pansy@imprintnext.com
	 * @date   11 Aug 2023
	 * @return json
	 */

	public function fetchImportCliparts($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'total_records' => 0,
			'records' => 0,
			'data' => [],
			'message' => message('Cliparts', 'not_found'),
		];

		try {
			// get categories with cliparts from the central server api.
			$endPoint = CENTRAL_ASSETS_BASEURL . "api/v1/cliparts";
			$allCategory = api_call_by_curl([
				"name" => $request->getQueryParam('name'),
				"page" => $request->getQueryParam('page'),
				"perpage" => $request->getQueryParam('perpage'),
				"order" => $request->getQueryParam('order'),
				"type" => $request->getQueryParam('type'),
				"primary_cat" => $request->getQueryParam('primary_cat'),
				"store_id" => $request->getQueryParam('store_id'),
				"cat_page" => $request->getQueryParam('cat_page'),
				"cat_perpage" => $request->getQueryParam('cat_perpage'),
				"cat_order" => $request->getQueryParam('cat_order'),
				"category" => $request->getQueryParam('category')
			], $endPoint, false, false);

			$allCategoryArray = $allCategory['data'];
			if (!empty($allCategoryArray)) {
				foreach ($allCategoryArray as $key => $cat) {
					$categoryInit = new Category();
					$result = $categoryInit->where('import_id', '=', $allCategoryArray[$key]['id'])->get();
					if ($result->count() > 0) {
						$allCategoryArray[$key]['is_imported'] = '1';
					} else {
						$allCategoryArray[$key]['is_imported'] = '0';
					}
				}
				$jsonResponse = [
					'status' => 1,
					'records' => count($allCategoryArray),
					'total_records' => $allCategory['total_records'],
					'data' => $allCategoryArray
				];
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			create_log('cliparts', 'error', [
				'message' => $e->getMessage(),
				'extra' => [
					'module' => 'Fetch category'
				]
			]);
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * PUT: Update catagories on multiple cliparts
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author mike@imprintnext.com
	 * @date   06 March 2025
	 * @return json
	 */
	public function updateCatagoriesCliparts($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = ['status' => 0, 'message' => message('Clipart', 'error')];
		try {
			// Get Store Specific Details from helper
			$getStoreDetails = get_store_details($request);
			$storeId = $getStoreDetails['store_id'];
			$allPostPutVars = $request->getParsedBody();
			$categoryIds = (isset($allPostPutVars['categories']) && $allPostPutVars['categories'] != "") ?
				$allPostPutVars['categories'] : NULL;
			$clipartIds = (isset($allPostPutVars['clipartIds']) && $allPostPutVars['clipartIds'] != "") ?
				$allPostPutVars['clipartIds'] : NULL;
			$clipartIds = str_replace(array('\'', '"', '[', ']', '<', '>'), ' ', $clipartIds);
			$clipartIdsArr = explode(",", $clipartIds);
			if (!empty($clipartIdsArr)) {
				$clipartInit = new Clipart();
				foreach ($clipartIdsArr as $clipartId) {
					$findClipArt = $clipartInit->where('xe_id', $clipartId);
					if (!$findClipArt->count()) {
						throw new \Exception('Clipart not found');
					}
					$getOldClipart = $findClipArt->first()->toArray();
					$oldCategoryArr = explode(",", $getOldClipart['category_id']);
					$newCategory = str_replace(array('\'', '"', '[', ']', '<', '>'), ' ', $categoryIds);
					$newCategoryArr = explode(",", $newCategory);
					$result = array_diff($oldCategoryArr, $newCategoryArr);
					foreach ($result as $res) {
						$clipartCount = new ClipartCategoryRelation();
						$countData = $clipartCount->where('category_id', '=', $res)->get()->toArray();
						$clipartCat = new Category();
						if (count($countData) == 1) {
							$flagList = ['asset_available_flag' => 0];
							$clipartCat->where('xe_id', '=', $res)->update($flagList);
						} else {
							$flagList = ['asset_available_flag' => 1];
							$clipartCat->where('xe_id', '=', $res)->update($flagList);
						}
					}
					
					$jsonResponse = ['status' => 1, 'message' => message('Clipart', 'updated')];

					/**
					 * Save category and subcategory data
					 * Category id format: [4,78,3]
					 */
					if ($categoryIds) {
						$this->saveClipartCategories($clipartId, $categoryIds);
					}
				}
				$this->memcache('deleteMulti', '', '', "cliparts_cat");
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			create_log('clipart', 'error', [
				'message' => $e->getMessage(),
				'extra' => ['module' => 'Updating a clipart']
			]);
		}

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

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