<?php

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

namespace App\Modules\Integration\Controllers;

use App\Components\Controllers\Component as ParentController;
use App\Modules\Settings\Controllers\SettingController;
use App\Modules\Settings\Models\Currency;
use App\Modules\Settings\Models\Language;
use App\Modules\Settings\Models\QuotationDynamicForm;
use App\Modules\Settings\Models\Setting;
use App\Modules\Settings\Models\Unit;
use App\Modules\Integration\Models\PluginSettings;
use Illuminate\Database\Capsule\Manager as DB;
use App\Modules\Orders\Controllers\OrdersController;
use App\Modules\Orders\Models\CatalogOrderRel;
use App\Modules\PrintProfiles\Models as PrintProfileModels;


/**
 * Setting Controller
 *
 * @category Class
 * @package  Setting
 * @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 IntegrationController extends ParentController
{

	/**
	 * GET: Check Plugin Integration data set or not
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   22 Feb 2022
	 * @return JSON
	 */
	public function pluginIntegration($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$params = ['domain_path' => API_URL];
		$test = false;
		$isCatalog = false;
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
		$isS3Enabled = $this->checkS3Settings($storeId);
		$centralServerApiResponse = api_call_by_curl($params, CATALOG_API_URL . 'catalog/services/api/v1/plugins', $test, $isCatalog);
		$data = $centralServerApiResponse['data'];
		$checkData = [];

		// Check plugin detail from setting table
		$settingInit = new Setting();
		foreach ($data as $key => $value) {
			$install = 0;
			$settingSlugInstalled = 0;
			$checkRecordSettings = $settingInit->where(['setting_key' =>  $value['slug_code']]);
			if ($checkRecordSettings->count() == 1) {
				$settingSlugInstalled = 1;
				$settingData = $checkRecordSettings->get()->toArray();
				$settingValue = json_clean_decode($settingData[0]['setting_value']);
				if (isset($settingValue['is_enabled']) && !$settingValue['is_enabled']) {
					$settingSlugInstalled = 0;
				}
				if (isset($settingValue['app_id']) && $settingValue['app_id'] == '') {
					$settingSlugInstalled = 0;
				}
			}
			////////////////////////////////////
			$pluginsObj = new PluginSettings();
			$checkRecordPlugins = $pluginsObj->where(['catalog_code' => $value['slug_code']])
				->where(['status' => 1]);
			///////////////////////////////////
			$pluinExpiresAt = time();
			if ($settingSlugInstalled || $checkRecordPlugins->count() || isset($value['auth_code'])  || isset($value['quick_auth_code']) || isset($value['spapi_oauth_code'])) {
				if ($checkRecordPlugins->count()) {
					$pluginDbData = $checkRecordPlugins->first()->toArray();
					$pluinExpiresAt = json_clean_decode($pluginDbData['settings'])['expires_at'];
				}
				$install = 1;
			}
			if ($value['slug_code'] == 'aws-s3' && $isS3Enabled == 1) {
				$install = 1;
				path('abs', 'setting') . 'stores/' . $storeId . '/S3Data.xml';
			}
			$checkData[$key]['slug_code'] = $value['slug_code'];
			$checkData[$key]['plugin_name'] = $value['plugin_name'];
			$checkData[$key]['sort'] = $value['sort_num'];
			$checkData[$key]['logo_url'] = $value['logo'];
			$checkData[$key]['description'] = $value['description'];
			$checkData[$key]['website_link'] = $value['website_link'];
			$checkData[$key]['install_link'] = $value['install_link'];
			$checkData[$key]['knowledge_base_link'] = $value['knowledge_base_link'];
			$checkData[$key]['price'] = $value['price'];
			$checkData[$key]['installed'] = $install > 0 ? 1 : 0;
			$checkData[$key]['is_active'] = $value['is_active'];
			$checkData[$key]['min_impnext_version'] = $value['min_impnext_version'];
			$checkData[$key]['category'] = $value['category'];

			if (isset($value['auth_code']) || isset($value['quick_auth_code']) || isset($value['spapi_oauth_code'])) {
				if (isset($value['auth_code']) && $value['auth_code'] != '') {
					$pluginData = [
						'catalog_code' => $value['slug_code'],
						'domain_imprint_path' => isset($value['domain_imprint_path']) ? $value['domain_imprint_path'] : '',
						'auth_code' => isset($value['auth_code']) ? $value['auth_code'] : '',
						'access_token' => isset($value['access_token']) ? $value['access_token'] : '',
						'expires_at' => isset($value['expires_at']) ? $value['expires_at'] : '',
						'refresh_token' => isset($value['refresh_token']) ? $value['refresh_token'] : '',
						'status' => 1,
					];
				}
				if (isset($value['quick_auth_code']) && $value['quick_auth_code'] != '') {
					$pluginData = [
						'catalog_code' => $value['slug_code'],
						'domain_imprint_path' => isset($value['quick_domain_imprint_path']) ? $value['quick_domain_imprint_path'] : '',
						'auth_code' => isset($value['quick_auth_code']) ? $value['quick_auth_code'] : '',
						'access_token' => isset($value['quick_access_token']) ? $value['quick_access_token'] : '',
						'expires_at' => isset($value['quick_expires_at']) ? $value['quick_expires_at'] : '',
						'refresh_token' => isset($value['quick_refresh_token']) ? $value['quick_refresh_token'] : '',
						'realmid' => isset($value['realmid']) ? $value['realmid'] : '',
						'generate_time' => isset($value['generate_time']) ? $value['generate_time'] : '',
						'status' => 1,
					];
				}
				if ($value['slug_code'] == 'quickbooks') {
					$quickbookExpireTime = $pluinExpiresAt = json_clean_decode($pluginDbData['settings'])['generate_time'];
				} elseif (isset($value['spapi_oauth_code']) && $value['spapi_oauth_code'] != '') {
					$pluginData = [
						'catalog_code' => $value['slug_code'],
						'domain_imprint_path' => isset($value['amazon_domain_imprint_path']) ? $value['amazon_domain_imprint_path'] : '',
						'version' => isset($value['version']) ? $value['version'] : '',
						'spapi_oauth_code' => isset($value['spapi_oauth_code']) ? $value['spapi_oauth_code'] : '',
						'selling_partner_id' => isset($value['selling_partner_id']) ? $value['selling_partner_id'] : '',
						'access_token' => isset($value['amazon_access_token']) ? $value['amazon_access_token'] : '',
						'refresh_token' => isset($value['amazon_refresh_token']) ? $value['amazon_refresh_token'] : '',
						'token_type' => isset($value['token_type']) ? $value['token_type'] : '',
						'date_time' => isset($value['date_time']) ? $value['date_time'] : '',
						'expires_at' => isset($value['amazon_expires_at']) ? $value['amazon_expires_at'] : '',
						'status' => 1,
					];
				}
				$pluginSettingData['catalog_code'] = $value['slug_code'];
				$pluginSettingData['settings'] = json_encode($pluginData, true);
				$pluginSettingData['created_date'] = date('Y-m-d H:i:s');
				$pluginSettingData['status'] = 1;

				$pluginsObj = new PluginSettings($pluginSettingData);
				$checkPlugins = $pluginsObj->where(['catalog_code' => $value['slug_code']]);
				if ($checkPlugins->count() == 0) {
					$pluginsObj->save();
				} else {
					if (($value['expires_at'] > time()  && $value['expires_at'] > $pluinExpiresAt) || $value['generate_time'] > $quickbookExpireTime) {
						$pluginsObj->where(["catalog_code" => $value['slug_code']])->update($pluginSettingData);
					} elseif ($value['slug_code'] == 'amazon' && $checkPlugins->count() == 1) {
						//and $value['amazon_expires_at']
						$pluginsObj->where(["catalog_code" => $value['slug_code']])->update($pluginSettingData);
					}
				}
			}
			if ($value['auth_code'] != '' || $value['quick_auth_code'] != '' || $value['spapi_oauth_code'] || isset($value['spapi_oauth_code'])) {
				$params = ['domain_path' => API_URL, 'slug_code' => $value['slug_code']];
				$centralServerApiResponse = api_call_by_curl($params, CATALOG_API_URL . 'catalog/services/api/v1/plugins/uninstall', $test = false, $isCatalog = false);
			}
		}
		$jsonResponse = [
			'status' => 1,
			'data' => $checkData,
		];

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

	/**
	 * GET: Plugin Install set or not
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   22 Feb 2022
	 * @return JSON
	 */
	public function pluginInstall($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Install Failed'
		];

		$getStoreDetails = get_store_details($request);
		$storeId = $getStoreDetails['store_id'];

		$allPostPutVars = $request->getParsedBody();

		if ($allPostPutVars['slug_code'] == "google_analytics") {

			$jsonDataArr = [
				'catalog_code' => trim($allPostPutVars['slug_code']),
				'measurement_id' => $allPostPutVars['measurement_id'],
				'is_enable' => ($allPostPutVars['is_enabled'] == "true")
			];

			if ($allPostPutVars['is_enabled'] == "true") {
				$settingLocation = path('abs', 'setting') . 'stores/' . $storeId . '/settings.json';
				$jsonData = file_get_contents($settingLocation);
				$jsonDecoded = json_decode($jsonData, true);
				$jsonDecoded['google_analytics_id'] = $allPostPutVars['measurement_id'];

				file_put_contents($settingLocation, json_encode($jsonDecoded));
			}
		}
		$status = isset($allPostPutVars['is_enabled']) &&
			($allPostPutVars['is_enabled'] == "true"  || $allPostPutVars['is_enabled'] == 1) ? 1 : 0;
		$pluginData = [
			'catalog_code' => trim($allPostPutVars['slug_code']),
			'settings' => !empty($jsonDataArr) ? json_encode($jsonDataArr, true) : "",
			'status' => $status
		];

		$pluginsObj = new PluginSettings($pluginData);
		$checkRecord = $pluginsObj->where(['catalog_code' => $allPostPutVars['slug_code']]);
		$pluginCount = $checkRecord->count();

		if ($pluginCount == 0) {
			$pluginsObj->save();
			$jsonResponse = [
				'status' => 1,
				'message' => 'Install Successfully'
			];
		} else {
			$checkRecord->update($pluginData);
			$jsonResponse = [
				'status' => 1,
				'message' => 'Install Successfully'
			];
		}

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

	/**
	 * GET: Plugin Uninstall
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   22 Feb 2022
	 * @return JSON
	 */
	public function pluginUninstall($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Uninstall Failed'
		];

		// get the store ID
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;

		// uninstall url on the central server
		$uninstallUrl = CATALOG_API_URL . 'catalog/services/api/v1/plugins/uninstall';
		$test = $isCatalog = false; // default param for uninstall url

		$allPostPutVars = $request->getParsedBody();
		$slugCode = $allPostPutVars['slug_code'];

		if ($slugCode == 'aws-s3') {
			$settingLocation = path('abs', 'setting') . 'stores/' . $storeId . '/S3Data.xml';
			$doc = new \DomDocument();
			$doc->formatOutput = true;
			$doc->load($settingLocation);
			$doc->getElementsByTagName("is_enabled")->item(0)->nodeValue = 'false';
			$doc->getElementsByTagName("is_enabled")->item(0)->nodeValue;
			if (!$doc->save($settingLocation)) {
				throw new \Exception("Plugin: aws-s3 could not be un-installed");
			} else {
				$settingUninstalStatus = 1;
			}
		} elseif ($slugCode == 'google_analytics') {
			$settingLocation = path('abs', 'setting') . 'stores/' . $storeId . '/settings.json';
			$jsonData = json_decode(file_get_contents($settingLocation), true);
			unset($jsonData['google_analytics_id']);
			file_put_contents($settingLocation, json_encode($jsonData, true));
		} else {
			if ($slugCode == 'catalog_providers') {
				// remove cronjob
				$supplierContoller = new CatalogSupplierController();
				$url = BASE_URL . 'update-central-catalog';
				// cron job every 30 minutes
				$job = "*/30 * * * * wget $url";

				$supplierContoller->removeCronJob($job);
			}
		}
		if ($settingUninstalStatus == 0) {
			$settingInit = new Setting();
			$settingUninstalStatus = $settingInit->where('setting_key', $slugCode)->where('store_id', $storeId)->delete();

			$pluginsInit = new PluginSettings();
			$pluginUninstalStatus = $pluginsInit->where('catalog_code', $slugCode)->update(["status" => 0]);
		}

		// unistall plugin from the central server
		$params = ['domain_path' => API_URL, 'slug_code' => $slugCode];
		api_call_by_curl($params, $uninstallUrl, $test, $isCatalog);

		if ($settingUninstalStatus || $pluginUninstalStatus) {
			$jsonResponse = [
				'status' => 1,
				'message' => 'Uninstall Successfully'
			];
		}

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

	/**
	 * GET: Plugin Uninstall
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   21 March 2022
	 * @return JSON
	 */
	public function shipstationOrderShipping($request, $response, $args)
	{
		$argsData = [];
		$ordersControllerObj = new OrdersController();
		$xml = $ordersControllerObj->getOrdersforshipstation($request, $response, $argsData);
		header('Content-Type: application/xml; charset=utf-8');
		echo $xml;
	}

	/**
	 * GET: SHipstation shipping update webhook call
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   21 March 2022
	 * @return JSON
	 */

	public function shipstationOrderShippingUpdate($request, $response, $args)
	{
		$allValues = $request->getParsedBody();
		$orderId = to_int($allValues->OrderID);
		$shipData =  json_encode($allValues, true);
		$catalogOrderRelObj = new CatalogOrderRel();
		$pluginId = $this->getPluginId('ship_station');
		$catalogOrderRelObj = $catalogOrderRelObj->select('*')
			->where('order_id', $orderId)
			->where('catalog_code', $pluginId);

		if ($catalogOrderRelObj->count() == 0) {
			$catlogProduct = [
				'order_id' => $orderId,
				'catalog_code' => $pluginId,
				'shipping' => $shipData,
				'status' => 1,
			];
			$catalogOrderRelObj = new CatalogOrderRel($catlogProduct);
			$catalogOrderRelObj->save();
			echo "new";
		} else {
			$catalogOrderRelObj->update(["shipping" => $shipData]);
			echo "Update";
		}
	}

	/**
	 * GET: Plugin install status
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   21 March 2022
	 * @return boolian
	 */

	public function getPluginInstallStatus($request, $response, $args)
	{
		$slugCode = $args['slug_code'];
		$serverStatusCode = OPERATION_OKAY;
		$pluginCount = 0;
		$pluginsInit = new PluginSettings();
		$pluginUninstalStatus = $pluginsInit->where('catalog_code', $slugCode)
			->where('status', 1);
		$pluginCount = $pluginUninstalStatus->count();

		$jsonResponse = [
			'status' => 1,
			'slug_code' => $slugCode,
			'installed' => $pluginCount,
		];
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * GET: Get plugin id
	 *
	 * @param $catalog_code  Slim's Request object
	 *
	 * @author steve@imprintnext.com
	 * @date   21 March 2022
	 * @return int
	 */
	public function getPluginId($catalog_code)
	{
		$pluginsInit = new PluginSettings();
		$data = $pluginsInit->where('catalog_code', $catalog_code)->first();
		return !empty($data) ? $data['xe_id'] : 0;
	}


	/**
	 * GET: Create customer in quickbook account
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   21 March 2022
	 * @return int
	 */
	public function createCustomerQuickbook($request, $response, $args)
	{
		$allPostPutVars = $request->getParsedBody();
		$quickBookObj = new QuickBookController();
		$quickBookObj->quickbookCustomerCreate($allPostPutVars);
	}

	/**
	 * GET: Create Order in quickbook account
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author steve@imprintnext.com
	 * @date   21 March 2022
	 * @return int
	 */
	public function createQuickbookInvoice($request, $response, $args)
	{
		$quickBookObj = new QuickBookController();
		$quickBookObj->quickbookInvoiceCreate($request);
	}
	/**
	 * GET: Mesment id from Google Analytics
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author sonali@imprintnext.com
	 * @date   25 Aug 2022
	 * @return int
	 */

	public function getAnalyticstId($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Google Analytics settings not saved',
		];
		try {
			$pluginsObj = new PluginSettings();
			$checkRecord = $pluginsObj->where(
				['catalog_code' => 'google_analytics']
			);
			if ($checkRecord->count() > 0) {
				$checkRecord = $checkRecord->first()->toArray();
				if ($checkRecord['status'] == 1) {
					$checkRecord = json_clean_decode($checkRecord['settings']);
					$jsonResponse = [
						'status' => 1,
						'data' => [
							'is_enabled' => $checkRecord['is_enable'],
							'measurement_id' => $checkRecord['is_enable'] === true ? $checkRecord['measurement_id'] : "",
						],
					];
				} else {
					$jsonResponse = [
						'status' => 1,
						'data' => [
							'is_enabled' => false,
							'measurement_id' => "",
						],
					];
				}
			} else {
				$jsonResponse = [
					'status' => 1,
					'data' => [
						'is_enabled' => false,
						'measurement_id' => "",
					],
				];
			}
		} catch (\Exception $e) {
			$jsonResponse['message'] = "wrong Google Analytics id";
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * GET: ImprintNext add-ons from central server
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@raixe.com
	 * @date   7 September 2022
	 * @return JSON
	 */
	public function getImpAddOns($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('ImprintNext add-ons', 'error'),
		];
		if (!empty($request->getQueryParam('current_version')) && !empty($request->getQueryParam('store_type')) && !empty($request->getQueryParam('store_version'))) {
			$params = array('current_version' => $request->getQueryParam('current_version'), 'store_type' => $request->getQueryParam('store_type'), 'store_version' => $request->getQueryParam('store_version'));
			$requestUrl = ADD_ONS_SERVER_URL . 'license_check/get_addon_list.php' . '?' . http_build_query($params);
			$addOnsArray = call_api($requestUrl, "GET", [], 1);
			if ($addOnsArray['status'] == 1) {
				$jsonResponse = ['status' => 1, 'data' => $addOnsArray['data']];
			} else {
				$jsonResponse = $addOnsArray;
			}
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * POST: Adding Dall-E details/ Update the Dall-E details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author sonali@imprintnext.com
	 * @date   22 Feb 2024
	 * @return JSON
	 */
	public function saveDalleImages($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'AI image generator is not setup'
		];
		$getStoreDetails = get_store_details($request);
		$storeId = $getStoreDetails['store_id'];
		$allPostPutVars = $request->getParsedBody();
		if ($allPostPutVars['is_enabled'] == "true") {
			$postData = [
				"model" => $allPostPutVars['model'],
				"prompt" => "The Indian flag is held by a boy",
				"n" => 1,
				"size" => $allPostPutVars['image_size']
			];
			$credentials['api_key'] = $allPostPutVars['api_key'];
			$curlStatus = $this->curlOpenAI($credentials, 'https://api.openai.com/v1/images/generations',  json_encode($postData, true), 'POST');
			$curlStatus = json_decode($curlStatus);
			if (empty($curlStatus->data)) {
				$jsonResponse = [
					'status' => 0,
					'message' => 'Incorrect API key or the OpenAI API rate limit is exceeded.'
				];
				return response($response, [
					'data' => $jsonResponse,
					'status' => $serverStatusCode
				]);
			}
			$jsonDataArr = [
				'api_key' => !empty($allPostPutVars['api_key']) ? $allPostPutVars['api_key'] : '',
				'no_of_image_per_prompt' => $allPostPutVars['no_of_image_per_prompt'],
				'quality' => !empty($allPostPutVars['quality']) ? $allPostPutVars['quality'] : '',
				'image_size' => $allPostPutVars['image_size'],
				'model' => $allPostPutVars['model'],
				'maximum_tries_per_user' => $allPostPutVars['maximum_tries_per_user'],
				'is_unlimited_tries' => $allPostPutVars['is_unlimited_tries'],
				'print_profile_ids' => $allPostPutVars['print_profile_ids'],
				'is_enable' => $allPostPutVars['is_enabled']
			];
			$printProfileIDs = json_decode($allPostPutVars['print_profile_ids'], true);
			$printProfieFeature = new PrintProfileModels\Feature();
			$checkFeatureDetails = $printProfieFeature->select('*')->where("slug", "=", "aiImage")->get()->toArray();
			if (empty($checkFeatureDetails)) {
				$printFeatures = [
					"asset_type_id" => 0,
					"name" => "AI image generator",
					"slug" => "aiImage",
				];
				$saveprintFeature = new PrintProfileModels\Feature($printFeatures);
				$saveprintFeature->save();
				$featureId = $saveprintFeature->xe_id;
			} else {
				$featureId = $checkFeatureDetails['0']['xe_id'];
			}
			// flush old print profile relations
			$profileFeatureRelIns = new PrintProfileModels\PrintProfileFeatureRel();
			$featureRelCount = $profileFeatureRelIns->select('print_profile_id')->where('feature_id', $featureId)->get()->toArray();
			if (count($featureRelCount) > 0) {
				$printProfIds = array_unique(array_column($featureRelCount, 'print_profile_id'));
				foreach ($printProfIds as $printID) {
					$printProfileLocation = path('abs', 'setting') . 'stores/' . $storeId . '/print_profile/' . $printID . '.json';
					$jsonPrint = json_decode(file_get_contents($printProfileLocation), true);
					$getSlug = array_column($jsonPrint['feature_data'], 'slug');
					$index = array_search("aiImage", $getSlug);
					if (!empty($index)) {
						unset($jsonPrint['feature_data'][$index]);
						file_put_contents($printProfileLocation, json_encode($jsonPrint, true));
					}
				}
				$profileFeatureRelIns->where(['feature_id' => $featureId])->delete();
			}
			// insert new print profile relations.
			foreach ($printProfileIDs as $printId) {
				if ($allPostPutVars['is_enabled'] == "true") {
					$savePrintProfFeature[] = [
						'print_profile_id' => $printId,
						'feature_id' => $featureId
					];
					$profileFeatureRelIns->insert($savePrintProfFeature);
				}
				$printProfileLocation = path('abs', 'setting') . 'stores/' . $storeId . '/print_profile/' . $printId . '.json';
				$jsonPrint = file_get_contents($printProfileLocation);
				$featureJson = json_decode($jsonPrint, true);
				$isFeatureAvailable = array_column($featureJson['feature_data'], 'slug');
				$imgData = [
					"id" => $featureId,
					"name" => "AI image generator",
					"slug" => "aiImage",
					"asset_type_id" => 0,
					"is_selected" => $allPostPutVars['is_enabled'] == "true" ? 1 : 0,
				];
				if (!in_array("aiImage", $isFeatureAvailable)) {
					array_push($featureJson['feature_data'], $imgData);
				} else {
					$index = array_search("aiImage", $isFeatureAvailable);
					$featureJson['feature_data'][$index] = $imgData;
				}
				file_put_contents($printProfileLocation, json_encode($featureJson));
			}
			$settingLocation = path('abs', 'setting') . 'stores/' . $storeId . '/settings.json';
			$jsonData = file_get_contents($settingLocation);
			$jsonDecoded = json_decode($jsonData, true);
			$jsonDecoded['image_setting']['image_generator'] = $jsonDataArr;
			$jsonDecoded['image_setting']['image_generator']['api_key'] = $this->getEncrptyValue($allPostPutVars['api_key']);
			unset($jsonDecoded['image_setting']['image_generator']['print_profile_ids']);
			file_put_contents($settingLocation, json_encode($jsonDecoded));
		} else {
			$printProfieFeature = new PrintProfileModels\Feature();
			$getfeatureId = $printProfieFeature->select('*')->where("slug", "=", "aiImage")->get()->toArray();
			$featureId = $getfeatureId[0]['xe_id'];
			$profileFeatureRelIns = new PrintProfileModels\PrintProfileFeatureRel();
			$getPrintids = $profileFeatureRelIns->where(['feature_id' => $featureId])->select('*')->get()->toArray();
			$getPrintids = array_unique(array_column($getPrintids, 'print_profile_id'));
			foreach ($getPrintids as $printID) {
				$printProfileLocation = path('abs', 'setting') . 'stores/' . $storeId . '/print_profile/' . $printID . '.json';
				$jsonPrint = json_decode(file_get_contents($printProfileLocation), true);
				$getSlug = array_column($jsonPrint['feature_data'], 'slug');
				$index = array_search("aiImage", $getSlug);
				if (!empty($index)) {
					unset($jsonPrint['feature_data'][$index]);
					file_put_contents($printProfileLocation, json_encode($jsonPrint, true));
				}
			}
			$profileFeatureRelIns->where(['feature_id' => $featureId])->delete();
			$printProfieFeature->where(['xe_id' => $featureId])->delete();
			$settingLocation = path('abs', 'setting') . 'stores/' . $storeId . '/settings.json';
			$jsonData = json_decode(file_get_contents($settingLocation), true);
			unset($jsonData['image_setting']['image_generator']);
			file_put_contents($settingLocation, json_encode($jsonData, true));
		}
		$status = isset($allPostPutVars['is_enabled']) && ($allPostPutVars['is_enabled'] == "true"  || $allPostPutVars['is_enabled'] == 1) ? 1 : 0;
		if ($status == 0) {
			//update status and json data
			$pluginsInit = new PluginSettings();
			$checkPluginTable = $pluginsInit->where(
				['catalog_code' => 'text_to_image']
			);
			if ($checkPluginTable->count() > 0) {
				$checkRecord = $checkPluginTable->first()->toArray();
				$checkRecord = json_clean_decode($checkRecord['settings']);
				$checkRecord['is_enable'] = 'false';
				$updatePluginData = [
					'settings' => json_encode($checkRecord, true),
					'status' => $status
				];
				$checkPluginTable->update($updatePluginData);

				$jsonResponse = [
					'status' => 1,
					'message' => 'AI image disable Successfully'
				];
			}

			return response($response, [
				'data' => $jsonResponse,
				'status' => $serverStatusCode
			]);
		}
		$pluginData = [
			'catalog_code' => trim($allPostPutVars['slug_code']),
			'settings' => !empty($jsonDataArr) ? json_encode($jsonDataArr, true) : "",
			'status' => $status
		];
		$pluginsObj = new PluginSettings($pluginData);
		$checkRecord = $pluginsObj->where(['catalog_code' => $allPostPutVars['slug_code']]);
		$pluginCount = $checkRecord->count();
		if ($pluginCount == 0) {
			$pluginsObj->save();
			$jsonResponse = [
				'status' => 1,
				'message' => 'AI image generator setup Successfully'
			];
		} else {
			$checkRecord->update($pluginData);
			$jsonResponse = [
				'status' => 1,
				'message' => 'AI image generator update Successfully'
			];
		}
		return response($response, [
			'data' => $jsonResponse,
			'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Get Dall-E details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author sonali@imprintnext.com
	 * @date   22 Feb 2024
	 * @return JSON
	 */
	public function getDalleImages($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Dall-E settings not saved',
		];
		try {
			$pluginsObj = new PluginSettings();
			$checkRecord = $pluginsObj->where(
				['catalog_code' => 'text_to_image']
			);
			if ($checkRecord->count() > 0) {
				$checkRecord = $checkRecord->first()->toArray();
				if ($checkRecord['status'] == 1) {
					$checkRecord = json_clean_decode($checkRecord['settings']);
					$printProfieFeature = new PrintProfileModels\Feature();
					$getfeatureId = $printProfieFeature->select('*')->where("slug", "=", "aiImage")->get()->toArray();
					if (!empty($getfeatureId)) {
						$featureId = $getfeatureId[0]['xe_id'];

						$profileFeatureRelIns = new PrintProfileModels\PrintProfileFeatureRel();
						$getPrintids = $profileFeatureRelIns->where(['feature_id' => $featureId])->select('*')->get()->toArray();
						$getPrintids = array_values(array_unique(array_column($getPrintids, 'print_profile_id')));
						$jsonResponse = [
							'status' => 1,
							'data' => [
								'api_key' => !empty($checkRecord['api_key']) ? $checkRecord['api_key'] : '',
								'no_of_image_per_prompt' => $checkRecord['no_of_image_per_prompt'],
								'image_size' => $checkRecord['image_size'],
								'model' => $checkRecord['model'],
								'quality' => !empty($checkRecord['quality']) ? $checkRecord['quality'] : '',
								'maximum_tries_per_user' => $checkRecord['maximum_tries_per_user'],
								'is_unlimited_tries' => $checkRecord['is_unlimited_tries'],
								'print_profile_ids' => $getPrintids,
								'is_enabled' => $checkRecord['is_enable']
							],
						];
					} else {
						$jsonResponse = [
							'status' => 1,
							'data' => [
								'is_enabled' => false
							],
						];
					}
				} else {
					$jsonResponse = [
						'status' => 1,
						'data' => [
							'is_enabled' => false
						],
					];
				}
			} else {
				$jsonResponse = [
					'status' => 1,
					'data' => [
						'is_enabled' => false
					],
				];
			}
		} catch (\Exception $e) {
			$jsonResponse['message'] = "wrong Dall-E settings details";
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	private function getEncrptyValue($string)
	{
		//make api key to encrpyt
		$encryptedVal = '';
		if ($string != '') {
			$key =  '5';
			$encrypte = $string;
			for ($i = 0, $k = strlen($encrypte); $i < $k; $i++) {
				$char = substr($encrypte, $i, 1);
				$char = chr(ord($char) + ord($key));
				$encryptedVal .= $char;
			}
			$encryptedVal = base64_encode($encryptedVal);
		}
		return $encryptedVal;
	}

	/*curl request to OpenAI
	* @author pansy@imprintnext.com
	* @date   27 May 2024 
	*/
	private function curlOpenAI($pluginData, $apiUrl, $paramArray, $method)
	{
		try {
			$requestHeaders = is_array($paramArray) ? [
				'Authorization: Bearer ' . $pluginData['api_key'],
				'Content-Type: multipart/form-data'
			] :  [
				'Authorization: Bearer ' . $pluginData['api_key'],
				'Content-Type: application/json'
			];
			$curl = curl_init();
			curl_setopt_array($curl, array(
				CURLOPT_URL => $apiUrl,
				CURLOPT_RETURNTRANSFER => true,
				CURLOPT_ENCODING => '',
				CURLOPT_MAXREDIRS => 10,
				CURLOPT_TIMEOUT => 0,
				CURLOPT_FOLLOWLOCATION => true,
				CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
				CURLOPT_CUSTOMREQUEST => $method
			));
			if (!empty($requestHeaders)) {
				curl_setopt($curl, CURLOPT_HTTPHEADER, $requestHeaders);
			}
			if ($method != 'GET' && !empty($paramArray)) {
				curl_setopt($curl, CURLOPT_POSTFIELDS, $paramArray);
			}
			$response = curl_exec($curl);
			$errno = curl_errno($curl);
			$error = curl_error($curl);

			curl_close($curl);

			if ($errno) {
				create_log('Request', 'error', [
					'message' => 'curl Request Error!',
					'extra' => ['errno' => $errno, 'error' => $error]
				]);
				return false;
			}
		} catch (\Exception $e) {
			die($e->getMessage());
		}

		return $response;
	}

	public function saveImagesToLocal($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Error while saving image to server',
		];
		$allPostPutVars = $request->getParsedBody();
		$prompt = !empty($allPostPutVars['text']) ? $allPostPutVars['text'] : "no image";
		// get Dalle API key from settings
		$pluginsObj = new PluginSettings();
		$checkRecord = $pluginsObj->where(
			['catalog_code' => 'text_to_image']
		);
		if ($checkRecord->count() > 0) {
			$checkRecord = $checkRecord->first()->toArray();
			if ($checkRecord['status'] == 1) {
				$credentials = json_clean_decode($checkRecord['settings']);
				$numOfImg = $credentials['no_of_image_per_prompt'];
				$imgSize = !empty($credentials['image_size']) ? $credentials['image_size'] : '1024x1024';
				$model = $credentials['model'];

				$postData = [
					"model" => $model,
					"prompt" => $prompt,
					"n" => (int)$numOfImg,
					"size" => $imgSize
				];
				$AIImages = $this->curlOpenAI($credentials, 'https://api.openai.com/v1/images/generations', json_encode($postData), 'POST');
				$allURLs = json_clean_decode($AIImages);
				if (!empty($allURLs['data'])) {
					$imageArr = array_column($allURLs['data'], "url");
				} else {
					$jsonResponse = [
						'status' => 0,
						'message' => 'No images could be created by AI',
					];
				}
			}
		}

		if (!is_dir(ASSETS_PATH_W . 'ai_images_temp/')) {
			mkdir(ASSETS_PATH_W . 'ai_images_temp/', 0755);
		}
		if (!empty($imageArr)) {
			$returnList = [];
			foreach ($imageArr as $imgKey => $AIURL) {
				// $AIURL = urldecode($AIURL);
				$localTempFile = ASSETS_PATH_W . 'ai_images_temp/' . basename(substr($AIURL, 0, strpos($AIURL, "?")));
				$localTempURL = ASSETS_PATH_R . 'ai_images_temp/' . basename(substr($AIURL, 0, strpos($AIURL, "?")));
				file_put_contents($localTempFile, fileGetContentsCurl($AIURL));
				$returnList[$imgKey]['url'] = $localTempURL;
			}
			$jsonResponse = [
				'status' => 1,
				'images' => $returnList,
			];
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	public function cleanOldImagesFromServer($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'message' => 'Temp AI images has been cleaned',
		];
		$targetTempDIR = ASSETS_PATH_W . 'ai_images_temp/';
		$files = glob($targetTempDIR . '*');
		$threshold = strtotime('-20 day');
		foreach ($files as $file) {
			if (is_file($file) && ($threshold >= filemtime($file))) {
				unlink($file);
			}
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * POST: create AI image variations 
	 *
	 * @param $request  image object
	 * @param $response Slim's Response object
	 *
	 * @author pansy@imprintnext.com
	 * @date   27 May 2024
	 * @return JSON
	 */
	public function createImageVariations($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'error occured',
		];
		$pluginsObj = new PluginSettings();
		$checkRecord = $pluginsObj->where(
			['catalog_code' => 'text_to_image']
		);
		if ($checkRecord->count() > 0) {
			$checkRecord = $checkRecord->first()->toArray();
			if ($checkRecord['status'] == 1) {
				$checkRecord = json_clean_decode($checkRecord['settings']);
				if ($checkRecord['is_enable'] && $checkRecord['model'] == 'dall-e-2') {
					$cfile = new \CURLFile($_FILES['image']['tmp_name'], '', basename($_FILES['image']['name']));
					$postData = [
						'model' => $checkRecord['model'],
						'image' => $cfile,
						'n' => (int)$checkRecord['no_of_image_per_prompt'],
						'size' => $checkRecord['image_size']
					];
					$responseData = $this->curlOpenAI($checkRecord, 'https://api.openai.com/v1/images/variations', $postData, 'POST');
					$createVariantImages = json_clean_decode($responseData, true);
					if (isset($createVariantImages['data']) && !empty($createVariantImages['data'])) {
						$imageArr = array_column($createVariantImages['data'], "url");
					} else {
						$jsonResponse = [
							'status' => 1,
							'message' => $createVariantImages['error']['message']
						];
					}
				}
			}
		}
		if (!is_dir(ASSETS_PATH_W . 'ai_images_temp/')) {
			mkdir(ASSETS_PATH_W . 'ai_images_temp/', 0755);
		}
		if (!empty($imageArr)) {
			$returnList = [];
			foreach ($imageArr as $imgKey => $AIURL) {
				$localTempFile = ASSETS_PATH_W . 'ai_images_temp/' . basename(substr($AIURL, 0, strpos($AIURL, "?")));
				$localTempURL = ASSETS_PATH_R . 'ai_images_temp/' . basename(substr($AIURL, 0, strpos($AIURL, "?")));
				file_put_contents($localTempFile, fileGetContentsCurl($AIURL));
				$returnList[$imgKey]['url'] = $localTempURL;
			}
			$jsonResponse = [
				'status' => 1,
				'images' => $returnList,
			];
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}


	/**
	 * POST: Check and Save memcached server details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author debashisd@raixe.com
	 * @date   23 May 2024
	 * @return JSON
	 * 
	 * @modified by divya@imprintnext.com
	 * @date 10 July 2024
	 */
	public function saveMemcachedSetting($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Memcache DOES NOT seem to be working!'
		];
		$settingLocation = path('abs', 'setting') . 'memcached.xml';
		// Check if PHP extension for "Memcached" enabled
		$allPostPutVars = $request->getParsedBody();
		$memCacheHost = !empty($allPostPutVars['host']) ? $allPostPutVars['host'] : "127.0.0.1";
		$memCachePort = !empty($allPostPutVars['port']) ? $allPostPutVars['port'] : 11211;
		$isEnabled = $allPostPutVars['is_enabled'];
		$catalogCode = 'memcache';

		if (class_exists('Memcached')) {
			if ($isEnabled == 1) {
				// Validate the host and port
				$memcached = new \Memcached;
				$getServers = $memcached->getServerList();
				if (empty($getServers)) {
					//planning to add different server for store and imprintnext data
					$memcached->addServers(array(
						array($memCacheHost, $memCachePort, 100)
					));
				} else {
					$hosts = array_column($getServers, "host");
					$ports = array_column($getServers, "port");
					if (!in_array($memCacheHost, $hosts) || !in_array($memCachePort, $ports)) {
						$memcached->addServers(array(
							array($memCacheHost, $memCachePort, 100)
						));
					}
				}
				//connect to instance using same weightage
				$isMemcacheAvailable = $memcached->addServer($memCacheHost, $memCachePort, 100);

				if ($isMemcacheAvailable) {
					$test = "testing Memcached";
					$memcached->set('test_imprint', $test);
					$memData = $memcached->get('test_imprint');
					if ($memData) {
						// save data in an xml to use further
						$dom = new \DomDocument();
						$memHost = $dom->createElement("memhost", $memCacheHost);
						$dom->appendChild($memHost);
						$domBucket = $dom->createElement("memport", $memCachePort);
						$dom->appendChild($domBucket);
						$domStatus = $dom->createElement("is_enabled", $isEnabled);
						$dom->appendChild($domStatus);
						$dom->save($settingLocation);
						$xmlContent = (string) file_exists($settingLocation) ? file_get_contents($settingLocation) : "";
						$xmlContent1 = str_replace('<?xml version="1.0"?>', '<?xml version="1.0"?><memcache>', $xmlContent);
						file_put_contents($settingLocation, $xmlContent1 . '</memcache>');

						if (!empty($xmlContent)) {
							$jsonDataArr = [
								'memhost' => $memCacheHost,
								'memport' => $memCachePort,
								'is_enable' => $isEnabled
							];

							$pluginData = [
								'catalog_code' => $catalogCode,
								'settings' => !empty($jsonDataArr) ? json_encode($jsonDataArr, true) : "",
								'status' => $isEnabled
							];

							$pluginsObj = new PluginSettings($pluginData);
							$checkRecord = $pluginsObj->where(['catalog_code' => $catalogCode]);
							$pluginCount = $checkRecord->count();

							if ($pluginCount == 0) {
								$pluginsObj->save();
							} else {

								$updatePluginData = [
									'settings' => json_encode($jsonDataArr, true),
									'status' => $isEnabled
								];
								$checkRecord->update($updatePluginData);
							}

							$jsonResponse = [
								'status' => 1,
								'message' => 'Memcache setting saved successfully.'
							];
						}
					} else {
						$jsonResponse['message'] = 'Unable to set/get data at given Memcached instance';
					}
				} else {
					$jsonResponse['message'] = 'Given host and port could not be connected';
				}
			} else {
				if (file_exists($settingLocation)) {
					$dom = new \DomDocument();
					$dom->load($settingLocation);
					$dom->getElementsByTagName("is_enabled")->item(0)->nodeValue = 0;
					$dom->save($settingLocation);

					$jsonDataArr = [
						'memhost' => $dom->getElementsByTagName("memhost")->item(0)->nodeValue,
						'memport' => $dom->getElementsByTagName("memport")->item(0)->nodeValue,
						'is_enable' => $isEnabled
					];

					$pluginsInit = new PluginSettings();
					$checkPluginTable = $pluginsInit->where(
						['catalog_code' => $catalogCode]
					);
					if ($checkPluginTable->count() > 0) {
						$updatePluginData = [
							'settings' => json_encode($jsonDataArr, true),
							'status' => $isEnabled
						];
						$checkPluginTable->update($updatePluginData);
						$jsonResponse = [
							'status' => 1,
							'message' => 'Memcache disabled Successfully.'
						];
					}
				} else {
					$jsonResponse = [
						'status' => 1,
						'message' => 'Memecache settings not saved.'
					];
				}
			}
		} else {
			$jsonResponse['message'] = 'Memcached Extension for PHP is not enabled';
		}
		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * GET: Memcache setting details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author divya@imprintnext.com
	 * @date   10 July 2024
	 * @return JSON
	 */

	public function getMemcachedSetting($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Error in Memcache settings.',
		];

		$pluginsObj = new PluginSettings();
		$checkRecord = $pluginsObj->where(
			['catalog_code' => 'memcache']
		);

		if ($checkRecord->count() > 0) {
			$checkRecord = $checkRecord->first()->toArray();
			if ($checkRecord['status'] == 1) {
				$memcacheSettings = json_clean_decode($checkRecord['settings'], true);
				$jsonResponse = [
					'status' => 1,
					'data' => [
						'host' => $memcacheSettings['memhost'],
						'port' => $memcacheSettings['memport'],
						'is_enabled' => $memcacheSettings['is_enable']
					],
				];
			} else {
				$jsonResponse = [
					'status' => 1,
					'data' => [
						'host' => null,
						'port' => null,
						'is_enabled' => 0
					],
				];
			}
		} else {
			$jsonResponse = [
				'status' => 1,
				'data' => [
					'host' => null,
					'port' => null,
					'is_enabled' => 0
				],
			];
		}

		return response(
			$response,
			['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * Delete all cache files from asset cache folder.
	 * Delete all memcached from server
	 * @param $request Slim's request object
	 * @param $response Slim's response object
	 * @author maria@imprintnext.com
	 * @return JSON
	 * @date   23 july 2024
	 */
	public function deleteAllCache($request, $response)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => 'Unable to clear cache.',
		];
		$folderPath = ASSETS_PATH_W . 'cache/design_assets/';
		try {
			$pluginsObj = new PluginSettings();
			$checkRecord = $pluginsObj->where(
				['catalog_code' => 'memcache']
			);
			if (!empty($checkRecord) && $checkRecord->count() > 0) {
				$checkRecord = $checkRecord->first()->toArray();
				if ($checkRecord['status'] == 1) {
					$memcacheSettings = json_clean_decode($checkRecord['settings'], true);
					$memHost = $memcacheSettings['memhost'];
					$memPort = $memcacheSettings['memport'];
					$memcached = new \Memcached;
					//Flush memcahed data
					$isMemcacheAvailable = $memcached->addServer($memHost, $memPort, 100);
					if (isset($isMemcacheAvailable) && !empty($isMemcacheAvailable)) {
						$memcached->flush();
					}
				}
			}
			//Flush all cache from asset cache folder
			$files = scandir($folderPath);
			if (is_dir($folderPath)) {
			foreach ($files as $file) {
				if ($file !== '.' && $file !== '..') {
					$filePath = $folderPath . $file;
					if (is_file($filePath)) {
							unlink($filePath);
							$jsonResponse = [
								'status' => 1,
								'message' => 'Caches deleted.',
							];
						}
					} else {
						$jsonResponse = [
							'status' => 0,
							'message' => 'No API cache found.',
						];
						}
					}
				}
			else {
			$jsonResponse = [
					'status' => 0,
					'message' => 'No API cache found.',
			];
			}
		} catch (\Exception $e) {
			echo 'Error: ',  $e->getMessage(), "\n";
		}

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