<?php
/**
 * Manage Color Swatches
 *
 * PHP version 5.6
 *
 * @category  Products
 * @package   Store
 * @author    Satyabrata <satyabratap@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */

namespace App\Modules\Settings\Controllers;

use App\Modules\Settings\Models\ColorSwatch;
use App\Modules\Settings\Models\ColorType;
use SwatchStoreSpace\Controllers\StoreColorVariantController;

/**
 * Color Swatches Controller
 *
 * @category Class
 * @package  Color_Swatch
 * @author   Satyabrata <satyabratap@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */
class ColorSwatchesController extends StoreColorVariantController {
	/**
	 * GET: Get color data from store
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author satyabratap@riaxe.com
	 * @date   5 Dec 2019
	 * @return A JSON Response
	 */
	public function getColorSwatch($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'color_id' => null,
			'message' => message('Variant Data', 'not_found'),
			'data' => []
		];
		$storeId = $request->getQueryParam('store_id');

		//GET MEMCACHEDATA
        $memcacheData = [];
        if (IS_MEMCACHE) {
            //MEMCACHED KEY
            $thisCacheKey = "colorswatch" . "_s" . $storeId;

            //Register MEMCACHED KEY in Local Cache
            $this->createUpdateMemCacheGroup('colorswatch', $thisCacheKey, 'SET');
            $memcacheData = $this->memcache("get", $thisCacheKey);
        }
		if (empty($memcacheData)) {
			$storeResponse = $this->getColorVariants($request, $response, $args);
			if (!empty($storeResponse)) {
				$variantData = $this->getColorSwatchData(
					$storeResponse['attribute_terms']
				);
				$jsonResponse = [
					'status' => 1,
					'records' => count($variantData),
					'color_id' => $storeResponse['color_id'],
					'data' => $variantData
				];
			}
			//SET IN MEMCACHED
            if (IS_MEMCACHE) {
                $this->memcache("set", $thisCacheKey, $jsonResponse);
            }
		}else{
			$jsonResponse = $memcacheData;
			if (MEM_MODE) {
                $jsonResponse['mode'] = 'memcache';
            }
		}
		
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode,
		]);
	}


	/**
	 * Post: Save Color in Store
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author satyabratap@riaxe.com
	 * @date   5 Oct 2019
	 * @return A JSON Response
	 */
	public function saveStoreColor($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Color Swatch', 'exist')
		];
		try {
			$allPostPutVars = $request->getParsedBody();
			$storeDetails = get_store_details($request);
			$storeId = $storeDetails['store_id'];
			$newColor = [];
			if (!empty($allPostPutVars['name']) && isset($allPostPutVars['color_id']) && $allPostPutVars['color_id'] > 0) {
				if (STORE_NAME == 'Prestashop') {
					//call prestashop store api
					$newColor = $this->saveColorValue($allPostPutVars);
				} else {
					$newColor = $this->saveColor($allPostPutVars['name'], $allPostPutVars['color_id'], $storeId);
				}
			}
			if (empty($newColor['id'])) {
				throw new \Exception('Unable to save color on the store');
			}
			$allPostPutVars['attribute_id'] = $newColor['id'];
			if (STORE_NAME == 'Prestashop') {
				$getUploadedFileName = '';
			} else {
				$uploadedFiles = $request->getUploadedFiles();
				if (!empty($uploadedFiles)) {
					$getUploadedFileName = do_upload(
						'upload',
						path('abs', 'swatch'),
						[150],
						'string'
					);
				}
			}
			$allPostPutVars['file_name'] = $getUploadedFileName;
			$colorSwatchInit = new ColorSwatch($allPostPutVars);
			if ($colorSwatchInit->save()) {
				$jsonResponse = [
					'status' => 1,
					'message' => message('Color Swatch', 'saved')
				];
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			$jsonResponse = [
				'status' => 0,
				'message' => message('Color Swatch', 'exception'),
				'exception' => show_exception() === true ?
					$e->getMessage() : '',
			];
		}
		//Flush Memcached\
		$this->memcache('deleteMulti', '', '', 'colorswatch');

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

	/**
	 * Post: Save Color Swatches
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author satyabratap@riaxe.com
	 * @date   5 Oct 2019
	 * @return A JSON Response
	 */
	public function saveColorSwatch($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Color Swatch', 'error')
		];
		try {
			$getStoreDetails = get_store_details($request);
			$isS3Enabled = $this->checkS3Settings($getStoreDetails['store_id']);
			$allPostPutVars = $request->getParsedBody();
			$cloudStorage = 0;
			if (isset($allPostPutVars['attribute_id'])) {
				$allPostPutVars['attribute_id'] = str_replace(' ', '_', strtolower($allPostPutVars['attribute_id']));
				$uploadedFiles = $request->getUploadedFiles();
				if (!empty($uploadedFiles)) {
					if (STORE_NAME == 'Prestashop') {
						//call prestashop store api
						$this->saveColorValue($allPostPutVars);
						$getUploadedFileName = '';
					} else {
						$getUploadedFileName = do_upload(
							'upload',
							path('abs', 'swatch'),
							[150],
							'string'
						);
						if ($isS3Enabled) {
							$cloudStorage = 1;
							$fileToUpload = path('abs', 'swatch') . $getUploadedFileName;
							$this->uploadFileToS3("swatch", $fileToUpload, $getStoreDetails['store_id']);
						}
					}
					$allPostPutVars['file_name'] = $getUploadedFileName;
					$allPostPutVars['cloud_storage'] = $cloudStorage;
				}
				$colorSwatchInit = new ColorSwatch($allPostPutVars);
				$colorSwatchInit->save();
				$jsonResponse = [
					'status' => 1,
					'message' => message('Color Swatch', 'saved')
				];
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			$jsonResponse = [
				'status' => 0,
				'message' => message('Color Swatch', 'exception'),
				'exception' => show_exception() === true ?
					$e->getMessage() : ''
			];
		}

		//Flush Memcached\
		$this->memcache('deleteMulti', '', '', 'colorswatch');

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

	/**
	 * Put: Update Product Images
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author satyabratap@riaxe.com
	 * @date   5 Oct 2019
	 * @return A JSON Response
	 */
	public function updateColorSwatch($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Color Swatch', 'error')
		];
		try {
			$allPostPutVars = $request->getParsedBody();
			$getStoreDetails = get_store_details($request);
			if (!empty($args['color_swatch_id']) && !empty($allPostPutVars['attribute_id'])) {
				$colorSwatchId = $args['color_swatch_id'];
				// get the color swatch, throw error if not found
				$colorSwatchInit = new ColorSwatch();
				if(strtolower(STORE_NAME) == "shopify"){
					if ($colorSwatchInit->where(['attribute_id' => $colorSwatchId])->count() > 0) {
						$colorSwatchData = $colorSwatchInit->where(['attribute_id' => $colorSwatchId])->first();
					} else {
						$colorSwatchData = [];
					}
				}else{
					if ($colorSwatchInit->where(['xe_id' => $colorSwatchId])->count() > 0) {
						$colorSwatchData = $colorSwatchInit->where(['xe_id' => $colorSwatchId])->first();
					} else {
						$colorSwatchData = [];
					}
				}
				$isS3Enabled = $this->checkS3Settings($getStoreDetails['store_id']);
				if (empty($colorSwatchData)) { //for Shopify add color is not there so edit swatch will check and add new color swatch to table
					$swatchData = [
						'attribute_id' => $allPostPutVars['attribute_id'],
						'hex_code' => $allPostPutVars['hex_code'],
						'color_type' => $allPostPutVars['color_type']
					];
					// upload new file
					$getUploadedFileName = do_upload('upload', path('abs', 'swatch'), [150], 'string');
					if (!empty($getUploadedFileName)) {
						if ($isS3Enabled) {
							$fileToUpload = path('abs', 'swatch') . $getUploadedFileName;
							$this->uploadFileToS3("swatch", $fileToUpload, $getStoreDetails['store_id']);
							$swatchData['cloud_storage'] = 1;
						}
						$swatchData['file_name'] = $getUploadedFileName;
						$swatchData['hex_code'] = '';
					}
					$colorSwatchInit = new ColorSwatch($swatchData);
					$colorSwatchInit->save();
				}else{
					$colorFile = $colorSwatchData->toArray();

				    // update data
					$swatchData = [
						'attribute_id' => $allPostPutVars['attribute_id'],
						'hex_code' => $allPostPutVars['hex_code'],
						'color_type' => $allPostPutVars['color_type']
					];
					// upload new file
					$getUploadedFileName = do_upload('upload', path('abs', 'swatch'), [150], 'string');
	
					// delete old file if present
					if (!empty($colorFile['file_name']) && (!empty($allPostPutVars['hex_code']) || !empty($getUploadedFileName))) {
						if ($colorFile['cloud_storage'] == 1) {
							//delete old file in S3
							$this->deleteS3File($colorFile['file_name'], $getStoreDetails['store_id']);
						} else {
							$this->deleteOldFile("color_swatches", "file_name", ['xe_id' => $colorSwatchId], path('abs', 'swatch'), false);
						}
						$swatchData['file_name'] = '';
					}
					if (!empty($getUploadedFileName)) {
						if ($colorFile['cloud_storage'] == 1 && $isS3Enabled) {
							$fileToUpload = path('abs', 'swatch') . $getUploadedFileName;
							$this->uploadFileToS3("swatch", $fileToUpload, $getStoreDetails['store_id']);
						}
						$swatchData['file_name'] = $getUploadedFileName;
						$swatchData['hex_code'] = '';
					}
					$colorSwatchData->update($swatchData);
				}
				$jsonResponse = [
					'status' => 1,
					'message' => message('Color Swatch', 'updated'),
					'color_swatch_id' => $colorSwatchId
				];
			}
		} catch (\Exception $e) {
			$serverStatusCode = EXCEPTION_OCCURED;
			$jsonResponse = [
				'status' => 0,
				'message' => message('Color Swatch', 'exception'),
				'exception' => show_exception() === true ? $e->getMessage() : ''
			];
		}

		//Flush Memcached\
		$this->memcache('deleteMulti', '', '', 'colorswatch');
		//Flush product memcached
		$this->memcache('deleteMulti', '', '', 'colorbyproductid');
		
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Get color type
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author satyabratap@riaxe.com
	 * @date   5 Dec 2019
	 * @return A JSON Response
	 */
	public function getColorType($request, $response) {
		$jsonResponse = [
			'status' => 0,
			'message' => message('Color Type', 'not_found')
		];
		$serverStatusCode = OPERATION_OKAY;
		$colorTypeInit = new ColorType();
		if ($colorTypeInit->count() > 0) {
			$jsonResponse = [
				'status' => 1,
				'data' => $colorTypeInit->get()
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
}
