<?php
/**
 * Manage Order Logs from Store end and Admin end
 *
 * PHP version 5.6
 *
 * @category  Store_Order
 * @package   Order
 * @author    Tanmaya Patra <tanmayap@riaxe.com>
 * @copyright 2019-2020 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 */
namespace App\Modules\Orders\Controllers;

use App\Components\Models\ProductionAbbriviations;
use App\Modules\Orders\Controllers\OrderDownloadController;
use App\Modules\Orders\Models\OrderItemToken;
use App\Modules\Orders\Models\OrderLog;
use App\Modules\Orders\Models\OrderLogFiles;
use App\Modules\Orders\Models\Orders;
use App\Modules\PurchaseOrder\Models\PurchaseOrderDetails;
use App\Modules\PurchaseOrder\Models\PurchaseOrderLineItemStatus;
use OrderStoreSpace\Controllers\StoreOrdersController;
use App\Modules\Settings\Models\Setting;
use App\Modules\Products\Controllers\ProductsController;
use App\Modules\Products\Controllers\ProductsCatalogController as ProductCatalog;
use App\Modules\Orders\Models\CatalogOrderRel;
use App\Modules\Integration\Controllers\PrintfulController;
use App\Modules\Integration\Controllers\IntegrationController;
use App\Modules\Settings\Models\Language;
use App\Modules\Orders\Models\ArtworkApproval;
use Illuminate\Database\Capsule\Manager as DB;
use App\Modules\Users\Controllers\UsersController;


/**
 * Order Log Controller
 *
 * @category Store_Order
 * @package  Order
 * @author   Tanmaya Patra <tanmayap@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 */
class OrdersController extends StoreOrdersController {
	/**
     * Initialize Language Content
     * 
     * @var array
     */
    public $languageContent = array();

	/**
	 * Initialize Constructor
	 */
	public function __construct($toolLang = '')
	{
		parent::__construct();
		$toolLang = (!is_object($toolLang)) ? $toolLang:'';
		$this->languageContent = $this->getDefaultLanguageContent('admin', $toolLang);
		// Anything you want to instantiate first can be written here
	}
	/**
	 * Get: Get Total Orders
	 *
	 * @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 Total Orders in Json format
	 */
	public function getOrderList($request, $response, $args, $returnType = 0)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Order Log', 'not_found'),
			'data' => []
		];

		$catalogCode = $request->getQueryParam('catalog_code') ? $request->getQueryParam('catalog_code') : '';

		// List Printful Orders
		if (isset($catalogCode) & $catalogCode != '') {
			$storeResponse = $this->listPrintfulOrder($request, $response, $args);
		} else { //List Normal Orders
			$storeResponse = $this->getStoreOrders($request, $response, $args);
		}
		$value = ['order_artwork_status'];
		$isArtworkEnabled = $this->getSettingStatus('artwork_approval', 6, $value);
		$ordersInit = new Orders();
		if (!empty($storeResponse)) {
			$removeFields = array_flip(['customer_id', 'production', 'order_total_quantity']);
			foreach ($storeResponse['order_details'] as $orderDetailsKey => $orderDetails) {
				// remove unused fields from the result
				$storeResponse['order_details'][$orderDetailsKey] = array_diff_key($storeResponse['order_details'][$orderDetailsKey], $removeFields);
				$ordersArtworkStatus = $ordersInit->where('order_id', $orderDetails['id'])->first();
				if ($isArtworkEnabled == 1) {
					$artworkStatus = $ordersArtworkStatus->artwork_status;
					$storeResponse['order_details'][$orderDetailsKey] += [
						'artwork_status' => (!empty($artworkStatus)) ? $artworkStatus : 'pending'
					];
				}

				if (strtolower(STORE_NAME) == "shopify") {
					$orderStatus = $ordersArtworkStatus->order_status;
					$storeResponse['order_details'][$orderDetailsKey]['status'] = (!empty($orderStatus)) ? $orderStatus : 'received';
				}
				$ordersPoStatus = $ordersInit
					->select(
						'quotations.xe_id as quotation_id',
						'quotations.quote_id as quotation_number'
					)
					->join('quotations', 'orders.order_id', '=', 'quotations.order_id')
					->where('orders.order_id', $orderDetails['id'])->first();
				$orderQuotationId = $ordersPoStatus->quotation_id;
				$ordeQuotationNumber = $ordersPoStatus->quotation_number;
				$storeResponse['order_details'][$orderDetailsKey] += [
					'quotation_id' => (isset($orderQuotationId) && $orderQuotationId != '') ? $orderQuotationId : 0,
					'quotation_number' => (isset($ordeQuotationNumber) && $ordeQuotationNumber != '') ? $ordeQuotationNumber : ''
				];
			}
			$jsonResponse = [
				'status' => 1,
				'total_records' => $storeResponse['total_records'],
				'records' => count($storeResponse['order_details']),
				'data' => $storeResponse['order_details'],
			];
		}

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

	/**
	 * Get: Get Total Orders
	 *
	 * @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 Total Orders in Json format
	 */
	public function getOrderDetails($request, $response, $args, $returnType = 0) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Order Log', 'not_found'),
			'data' => [],
		];
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
		if(!isset($args['list_exclude'])){
			$args['list_exclude'] = [];
		}
		$storeResponse = $this->getStoreOrders($request, $response, $args);
		$value = ['order_artwork_status'];
		$isArtworkEnabled = $this->getSettingStatus('artwork_approval', 6, $value);
		$ordersInit = new Orders();	
		
		if (!empty($args['id']) && !empty($storeResponse)) {
			//Printful Shipping status
            $IntegrationObj = new IntegrationController();
            $printfulPluginId = $IntegrationObj->getPluginId('printful');
           
			if ($printfulPluginId > 0){
				$storeResponse['order_details']['printful'] = $this->getPrintfulOrderStatus($printfulPluginId, $args['id']);				
            }
			//shipstation Shipping status
            $shipstationPluginId = $IntegrationObj->getPluginId('ship_station');
           
			if ($shipstationPluginId > 0){
            	$storeResponse['order_details']['ship_station'] = $this->shipStationOrder($shipstationPluginId, $args['id']);				
            }
			
			if (!in_array('base_code', $args['list_exclude'])) {
				/** generate base code */
				$orderId = "order-".$args['id'];
				$barCodePath =  ASSETS_PATH_W.'bar_codes/'.$orderId.'.png';
				
				if (!file_exists($barCodePath)) {
					$this->createOrderBarCode($args['id']);
				}
			}

			//Get artwork status
			$ordersArtworkStatus = $ordersInit->where('order_id', $args['id']);
			$artworkStatusData = $ordersArtworkStatus->first();
			if ($isArtworkEnabled == 1) {
				$token = 'order_id=' . $args['id'].'&store_id='.$storeId;
				$token = base64_encode($token);
				// $url = QUOTATION_REVIEW . '/quotation/art-work?token=' . $token . '&artwork_type=order';
				$url = API_URL . 'quotation/art-work?token=' . $token . '&artwork_type=order';
				$storeResponse['order_details'] += ['public_url' => $url];
				$storeResponse['order_details'] += ['artwork_status' => $artworkStatusData->artwork_status];
			}
			$storeResponse['order_details'] += ['po_status' => (!empty($artworkStatusData->po_status)) ? $artworkStatusData->po_status : 0];
			$storeResponse['order_details'] += ['production_status' => (!empty($artworkStatusData->production_status)) ? $artworkStatusData->production_status : 0];
			$storeResponse['order_details'] +=['barcode_url' => ASSETS_PATH_R.'bar_codes/'.$orderId.'.png'];

			if (!in_array('poStatus', $args['list_exclude'])) {
				
				if ($artworkStatusData->po_status == 0) {
					$storeResponse['order_details'] += ['po_status_name' => ''];
					$storeResponse['order_details'] += ['po_status_color' => ''];
				} else {
					$poStatusDetails = $this->getOrderPoStatusDetails($args['id'], $artworkStatusData->po_status, $storeId);
					$po_status_name = isset($poStatusDetails['status_name']) ? $poStatusDetails['status_name']: '';
					$po_status_color = isset($poStatusDetails['color_code']) ? $poStatusDetails['color_code']: '';
					$storeResponse['order_details'] += ['po_status_name' => $po_status_name];
					$storeResponse['order_details'] += ['po_status_color' => $po_status_color];
				}
			}
			$thisOrderId = strtolower(STORE_NAME) != "shopify" ? $storeResponse['order_details']['id'] : $storeResponse['order_details']['order_number'];
			
			// Call to internal function to generate Decorate Data
			$storeResponse = $this->generateDecoratedData($request,$storeResponse, $thisOrderId, $args);

			if (empty($storeResponse['notes'])) {
				$storeResponse['order_details']['notes'][0] = "N/A";
			} else {
				$storeResponse['order_details']['notes'] = $storeResponse['notes'];
			}
			
			if (isset($args['is_return']) && $args['is_return']) {
				return $storeResponse;
			}else {
				$jsonResponse = [
					'status' => 1,
					'total_records' => $storeResponse['total_records'],
					'data' => $storeResponse['order_details'],
				];
			}
		}

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

	/**
	 * Post: Save Order Log data
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author satyabratap@riaxe.com
	 * @date   5 Oct 2019
	 * @return Order logs in Json format
	 */
	public function saveOrderLogs($request, $response) {
		$serverStatusCode = OPERATION_OKAY;
		$allPostPutVars = $request->getParsedBody();
		$jsonResponse = [
			'status' => 0,
			'message' => message('Order Log', 'error'),
		];
		$storeDetails = get_store_details($request);
		$orderLogsJson = $allPostPutVars['log_data'];
		$orderLogsArray = json_clean_decode($orderLogsJson, true);
		if (!empty($orderLogsArray['order_id'])) {
			$saveOrderLog = new OrderLog(
				[
					'order_id' => $orderLogsArray['order_id'],
					'agent_type' => $orderLogsArray['agent_type'],
					'agent_id' => $orderLogsArray['agent_id'],
					'store_id' => $orderLogsArray['store_id'],
					'message' => $orderLogsArray['message'],
					'log_type' => $orderLogsArray['log_type'],
					'artwork_status' => $orderLogsArray['artwork_status'],
					'status' => $orderLogsArray['status']
				]
			);

			if ($saveOrderLog->save()) {
				$orderLogInsertId = $saveOrderLog->xe_id;
				if (!empty($orderLogsArray['files'])) {
					foreach ($orderLogsArray['files'] as $fileData) {
						// Start saving each sides
						$imageUploadIndex = $fileData['image_upload_data'];
						// If image resource was given then upload the image
						// into the specified folder
						$getFiles = do_upload(
							$imageUploadIndex, path('abs', 'order_log'), [150], 'string'
						);
						// Setup data for Saving/updating
						$orderLogFiles = [
							'order_log_id' => $orderLogInsertId,
						];

						// If File was choosen from frontend then only
						// save/update the image or skip the image saving
						if (!empty($getFiles)) {
							$orderLogFiles['file_name'] = $getFiles;
						}
						// Insert Order Log Files
						$saveOrderLogFile = new OrderLogFiles($orderLogFiles);
						$saveOrderLogFile->save();
					}
				}
				$jsonResponse = [
					'status' => 1,
					'order_log_id' => $orderLogInsertId,
					'message' => message('Order Log', 'saved'),
				];
				if ($orderLogsArray['log_type'] == 'artwork'
					&& $orderLogsArray['agent_type'] == 'admin'
				) {
					// Sending mail
					$token = 'order_id=' . $orderLogsArray['order_id']. '&store_id='. $storeDetails['store_id'];
					$token = base64_encode($token);
					// $url = QUOTATION_REVIEW . '/quotation/art-work?token=' . $token . '&artwork_type=order';
					$url = API_URL . 'quotation/art-work?token=' . $token . '&artwork_type=order';
					// Send mail
					$mailData = [
						'agent_email' => $orderLogsArray['agent_email'],
						'agent_name' => $orderLogsArray['agent_name'],
						'customer_email' => $orderLogsArray['customer_email'],
						'customer_name' => $orderLogsArray['customer_name'],
						'url' => $url,
					];
					//Send approval mail to customer
					if ($this->orderApproveMail($mailData)) {
						$jsonResponse = [
							'status' => 1,
							'order_log_id' => $orderLogInsertId,
							'url' => $url,
							'message' => message('Order Log', 'saved'),
						];
					}
				}
			}
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
	/**
	 * GET: Get all Order Logs of a single order
	 *
	 * @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 Order Logs in Json format
	 */
	public function getOrderLogs($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$totalOrderLogs = [];
		$processInAppLog = [];
		$orderLogInit = new OrderLog();
		$initOrderLog = $orderLogInit->with('files');
		if (isset($args['id']) && $args['id'] > 0) {
			$initOrderLog->where('order_id', $args['id']);
		}
		//For customer view
		$viewType = $request->getQueryParam('type');
		if (isset($viewType) && $viewType == 'customer') {
			$initOrderLog->where('log_type', 'artwork');
		}
		// Check Artwork Setting is enabled or not
		$settingValue = ['order_artwork_status'];
		$isArtworkEnabled = $this->getSettingStatus('artwork_approval', 6, $settingValue);
		if ($isArtworkEnabled == 0) {
			$initOrderLog->whereNotIn('log_type', ['artwork']);
		}

		if ($initOrderLog->count() > 0) {
			$inAppOrderLogs = $initOrderLog->orderBy('xe_id', 'desc')
				->get()->toArray();
			foreach ($inAppOrderLogs as $inAppLogkey => $inAppLog) {
				$processInAppLog[$inAppLogkey] = [
					'id' => $inAppLog['xe_id'],
					'order_id' => $inAppLog['order_id'],
					'agent_type' => $inAppLog['agent_type'],
					'agent_id' => $inAppLog['agent_id'],
					'store_id' => $inAppLog['store_id'],
					'message' => $inAppLog['message'],
					'log_type' => $inAppLog['log_type'],
					'status' => $inAppLog['status'],
					'artwork_status' => $inAppLog['artwork_status'],
					'created_at' => $inAppLog['created_at'],
					'updated_at' => $inAppLog['updated_at'],
					'files' => $inAppLog['files'],
					'order_artwork_id' => $inAppLog['artwork_approval_id'],
				];
			}
		}

		// Get Logs from Store
		if (isset($viewType) && $viewType == 'customer') {
			$totalOrderLogs = $processInAppLog;
		} else {
			$storeLogs = [];
			$storeLogs = $this->getStoreLogs($request, $response, $args);
			foreach ($storeLogs as $logKey => $log) {
				if ($log['log_type'] == 'order_status') {
					$storeLogs[$logKey]['log_type'] = 'Order status';
					$storeLogs[$logKey]['created_at'] = $log['updated_at'];
				} elseif ($log['log_type'] == 'payment_status') {
					$storeLogs[$logKey]['log_type'] = 'Payment status';
				}
			}
				$totalOrderLogs = array_merge($processInAppLog, $storeLogs);			
		}

		// Sort the array by Created Date and time
		usort($totalOrderLogs, 'date_compare');

		if (is_array($totalOrderLogs) && !empty($totalOrderLogs) > 0) {
			$jsonResponse = [
				'status' => 1,
				'data' => $totalOrderLogs,
			];
		}else{
			$jsonResponse = [
				'status' => 1,
				'data' => [],
				'message' => message('Order Log', 'not_found'),
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: get order details for dashboard
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Args object
	 *
	 * @author debashrib@riaxe.com
	 * @date   27 Jan 2020
	 * @return Order data in Json format
	 */
	public function getOrdersGraph($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'message' => message('Order Graph', 'not_found'),
		];
		$refundArr = [];
		$totalRevenue = 0.00;
		$totalRefund = 0.00;
		// Fixed order graph issue for wc
		$args['is_graph'] = 1;
		$ordersDataArr = $this->getStoreOrders($request, $response, $args);
		if (is_valid_array($ordersDataArr)) {
			$orderData = $ordersDataArr['order_details'];
			$totalAmountArr = array_column($orderData, 'total_amount');
			$totalRevenue = array_sum($totalAmountArr);

			$refundArr = array_filter(
				$orderData, function ($item) {
					if ($item['status'] == 'refunded') {
						return true;
					}
				}
			);
			if (is_valid_array($refundArr)) {
				$totalRefundAmountArr = array_column($refundArr, 'total_amount');
				$totalRefund = array_sum($totalRefundAmountArr);
			}
			$repeatCustomerRate = $this->getrepeatCustomerRate($ordersDataArr);
			$ordersData = [
				"total_revenue" => number_format((float) $totalRevenue, 2, '.', ''),
				"refunds" => number_format((float) $totalRefund, 2, '.', ''),
				"repeat_customer_rate" => $repeatCustomerRate,
				"order_data" => $orderData,
			];
			$jsonResponse = [
				'status' => 1,
				'data' => $ordersData
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Generate Order Files
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Args object
	 *
	 * @author malay@riaxe.com
	 * @date   05 March 2020
	 * @return array json
	 */
	public function generateOrderFiles($request, $response, $args) {
		ignore_user_abort(true);
        ini_set('memory_limit', '1024M');
		$serverStatusCode = OPERATION_OKAY;
		// For encripted token
		$token = $args['id'];
		if (!empty($token)) {
			$decryptData = decryption($token);
			if (!empty($decryptData)) {
                $orderIdStoreIdArray = explode("@", $decryptData);
                if (!empty($orderIdStoreIdArray) && $orderIdStoreIdArray[0] != "") {
                    $orderId = $orderIdStoreIdArray[0];
                    if (array_key_exists(1, $orderIdStoreIdArray)) {
                        $storeId = $orderIdStoreIdArray[1];
                    } else {
                    	$storeId = 1;
                    }
                }
	        }
	        $args['id'] = $orderId;
			$args['store_id'] = $storeId;
		}
		$orderFilePath = ASSETS_PATH_W . 'orders/order_view';
		$orderFileAbsPath = $orderFilePath . '/' . $orderId . '.json';
		if (!is_dir($orderFilePath)) {
            mkdir($orderFilePath, 0755, true);
        }
		if (!file_exists($orderFileAbsPath)) {
			$orderDetails = $this->getStoreOrders($request, $response, $args);
			file_put_contents($orderFileAbsPath, json_encode($orderDetails));
		} else {
			$jsonContent = read_file($orderFileAbsPath);
			$orderDetails = json_clean_decode($jsonContent, true);
		}
		$orderId = isset($orderDetails['order_details']['id']) ? $orderDetails['order_details']['id'] : 0;
		$orderNumber = isset($orderDetails['order_details']['order_number']) ? $orderDetails['order_details']['order_number'] : 0;
		$storeId = isset($orderDetails['order_details']['store_id']) ? $orderDetails['order_details']['store_id'] : 1;
		$customerId = (isset($orderDetails['order_details']['customer_id']) && $orderDetails['order_details']['customer_id'] != '' && $orderDetails['order_details']['customer_id'] != null) ? $orderDetails['order_details']['customer_id'] : 0;
		if (!empty($orderDetails['order_details']['orders'])) {
			foreach ($orderDetails['order_details']['orders'] as $items) {
				$this->updateMostusedAssets($items['custom_design_id']);
				if (strtolower(STORE_NAME) == "woocommerce") {
					$this->updatePrintMethodsByRefId($items['id'],$items['custom_design_id']);
				}
			}
		}
		if (!empty($orderDetails)) {
			//Initiate order download controller
			$orderDwonloadObj = new OrderDownloadController();
			$isS3Enabled = $this->checkS3Settings($storeId);
			$orderDwonloadObj->createOrderAssetFile($args, $orderDetails,$request, $response, false, $isS3Enabled);
			$orderBarCode = "order-".$orderId;
			$barCodePath =  ASSETS_PATH_W.'bar_codes/'.$orderBarCode.'.png';
			if (!file_exists($barCodePath)) {
				$this->createOrderBarCode($orderId);
			}
			if ($isS3Enabled) {
				$orderIDDIR = (strtolower(STORE_NAME) == "shopify")?$orderNumber:$orderId;
				$thisOrderDIR = path('abs', 'order') . $orderIDDIR;
				if(strtolower(STORE_NAME) == "bigcommerce"){
					sleep(4);
				}
				$this->uploadDIRToS3Recurse("/assets/orders/".$orderIDDIR, $thisOrderDIR, $storeId);
			}
		}
		if ($orderId > 0 && $storeId > 0 && $customerId >= 0) {
			//add data to orders table
			$this->saveDataForOrder($orderId, $storeId, $customerId, $orderNumber);
		}

		// Create MEMCACHED for order details.
		if (IS_MEMCACHE) {
			$this->getStoreOrders($request, $response, $args);

			$args['ui'] = 1;
			$this->getStoreOrders($request, $response, $args);
		}
		return response($response, [
			'data' => $orderDetails, 'status' => $serverStatusCode
		]);
	}

	/**
	 * Send Order Approval Mail
	 *
	 * @param $mailData Array of all mail information
	 *
	 * @author debashrib@riaxe.com
	 * @date   18 March 2020
	 * @return boolean
	 */
	private function orderApproveMail($mailData) {
		$prev = "<!DOCTYPE html><html><title>Quote</title><style>a{color:#1b41c7}</style><body><table style='border-collapse: collapse; width: 100%; max-width: 835px; min-width: 320px;'><tbody><tr><td valign='top' style='padding:0 0px'><table cellspacing='0' cellpadding='0' border='0' align='center' style='border-collapse:collapse;border-radius:3px;color:#545454;font-family:Helvetica Neue,Arial,sans-serif;font-size:13px;line-height:20px;margin:0 auto;width:100%'><tbody><tr><td valign='top'>";

		$next = "</td></tr></tbody></table></td></tr><tr><td valign='top' height='20'/></tr></tbody></table></body></html>";

		$html = "<table cellspacing='0' cellpadding='0' border='0' style='border-collapse:collapse;border-color:#dddddd;border-radius:0 0 3px 3px;border-style:solid solid none; padding: 10px; display: block;color:#525252;'><tbody><tr><td bgcolor='white' style='background:white;border-radius:0 0 3px 3px;color:#525252;font-family:Helvetica Neue,Arial,sans-serif;font-size:15px;line-height:22px;overflow:hidden;padding:10px 10px 10px'><p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'>Thank you for your order request.</strong></p><p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'>We have evaluated your project details and created an artwork for your review. Please click the link below to review the artwork we have proposed:</strong></p><p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'><br/>Link : <a target='_blank' href='" . $mailData['url'] . "'> " . $mailData['url'] . " </a> <br/></p><p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252;'>Once you have looked over your order, you can go ahead and approve or decline it. If you need any more help, please chat with the sales associate.</p><p align='left' style='line-height:1.5;margin:10px 0 5px;text-align:left!important;color:#525252'>Thanks!</p><p align='left' style='line-height:1.5;margin:0 0 5px;text-align:left!important;color:#525252'>" . $mailData['name'] . "</p></td></tr></tbody></table>";
		$emailBody = $prev . $html . $next;
		//Get smtp email setting data for sending email
		$smtpEmailSettingData = call_curl([],
			'settings', 'GET'
		);
		$smtpData = $smtpEmailSettingData['general_settings']['smtp_details'];
		$emailData = $smtpEmailSettingData['general_settings']['email_address_details'];
		$fromName = $emailData['from_email'];
		$fromEmail = $smtpData['smtp_from'];
		$replyToEmail = $emailData['to_email'];
		$mailContaint = ['from' => ['email' => $fromEmail, 'name' => $fromName],
			'recipients' => ['to' => ['email' => $mailData['customer_email'],
				'name' => $mailData['customer_name']],
				'reply_to' => ['email' => $replyToEmail,
					'name' => $replyToEmail],
			],
			'subject' => 'Approve your order',
			'body' => $emailBody,
			'smptData' => $smtpData,
		];
		$mailResponse = email($mailContaint);
		if (!empty($mailResponse['status']) && $mailResponse['status'] == 1) {
			return true;
		}
		return false;
	}

	/**
	 * PUT : Change Artwork Status
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author debashrib@riaxe.com
	 * @date   18 March 2020
	 * @return json response wheather data is updated or not
	 */
	public function updateOrderArtworkStatus($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Artwork Status ', 'error'),
		];
		$getStoreDetails = get_store_details($request);
		$updateData = $request->getParsedBody();
		$orderStatus = ['artwork_status' => $updateData['artwork_status']];
		if (!empty($args['id']) && $args['id'] > 0) {
			$isCreateProductionJob = false;
			$ordersInit = new Orders();
			$getArtworkStatus = $ordersInit->where('order_id', $args['id']);
			if ($getArtworkStatus->count() > 0) {
				$ordersInit->where('order_id', $args['id'])
					->update($orderStatus);
				//Create production job
				if ($updateData['artwork_status'] == 'approved') {
					//Get global order setting
					$settingInit = new Setting();
					$orderSetting =  $settingInit->select('setting_value')->where([
						'type' => 6,
						'store_id' => $getStoreDetails['store_id'],
						'setting_key' => 'artwork_approval'
					]);
					$isArtworkApproval = 0;
					if ($orderSetting->count() > 0) {
						$orderSettingData = json_clean_decode($orderSetting->first(), true);
						$orderSettingData = json_clean_decode($orderSettingData['setting_value'],true);
						$isArtworkApproval = $orderSettingData['order_artwork_status'];
					}
					//Get production setting
					$productionSettingData = $this->getProductionSetting($request, $response, ['module_id' => 4, 'return_type' => 1]);
					$productionSettingData = $productionSettingData['data'];
					$isAutomaticJobCreation = (isset($productionSettingData['is_automatic_job_creation'])) ? $productionSettingData['is_automatic_job_creation'] : 0;
					$purchaseOrderMandetory = (isset($productionSettingData['purchase_order_mandetory'])) ? $productionSettingData['purchase_order_mandetory'] : 0;
					if ($isAutomaticJobCreation == 1 && $isArtworkApproval == 1) {
						$checkPoStatus = $ordersInit->where([
							'order_id' => $args['id'],
							'po_status' => 3,
						]);
						if ($purchaseOrderMandetory != 1) {
							$isCreateProductionJob = true;
						} elseif ($purchaseOrderMandetory == 1 && $checkPoStatus->count() > 0) {
							$isCreateProductionJob = true;
						}
					}
				}

			}
			$jsonResponse = [
				'status' => 1,
				'order_id' => $args['id'],
				'is_create_production_job' => $isCreateProductionJob,
				'message' => message('Artwork Status', 'updated'),
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET : Only for Shopify use to delete/hide duplicate products
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author debashisd@riaxe.com
	 * @date   21 April 2020
	 * @return json response wheather product is updated or not
	 */
	public function editShopifyProduct($request, $response, $args) {
		$updateData = $this->editCustomProduct($request, $response, $args);
		return json_encode($updateData);
	}

	/**
	 * GET: Generate Order Packing Slip
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Args object
	 *
	 * @author mike@imprintnext.com
	 * @date   21 May 2020
	 * @return array json
	 */
	public function downloadPackingSlip($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Packing Slip Download', 'error'),
		];
		$orderIncrementId = $request->getQueryParam('order_increment_id') ? $request->getQueryParam('order_increment_id') : 0;
		$storeId = $request->getQueryParam('store_id') ? $request->getQueryParam('store_id') : 1;
		$orderAssetPath = path('abs', 'order') . $orderIncrementId;
		if (is_dir($orderAssetPath)) {
			$orderId = $orderIncrementId;
		} else {
			$orderId = $args['id'];
		}
		$pdfLanguage = $this->languageContent['order-pdf'];
		$barCodeImageUrl =  ASSETS_PATH_R . 'bar_codes/order-' . $args['id'] . '.png';
		
		//Get order seeting from general settings
		$settingInit = new \App\Modules\Settings\Models\Setting();
		$getSettings = $settingInit->where('type', '>', 0);
		$orderSetting = [];
		$packageSlipNotes = $pakageSlipAddress = $packingSlipLogo = '';
		$isProductImage = false;
		$isPackageSlipNotes = false;

		// Fetch language Type
		$languageInit = new Language();
        $where = ['type' => 'admin', 'is_default' => 1, 'store_id'=> $storeId];
        $getLanguage = $languageInit->where($where)->first()->toArray();
		// End
        $rtlLeftAlign = "right";
        $rtlRightAlign = "left";
 		if ($getLanguage['name'] == 'Arabic') {
 			$rtlLeftAlign = "left";
        	$rtlRightAlign = "right";
 		}

		$packageSlipStoreUrl = '';

		if ($getSettings->count() > 0) {
			$data = $getSettings->get();
			foreach ($data as $value) {
				if ($value['type'] == 6) {
					$packingSlipLogo = $this->getPackingSlipLogo($storeId);
					$orderSetting['packing_slip_logo'] = $packingSlipLogo;
					$orderSetting[$value['setting_key']] = json_clean_decode(
						$value['setting_value'],
						true
					) ? json_clean_decode(
						$value['setting_value'],
						true
					) : $value['setting_value'];
				}
			}
			if ($orderSetting['package_slip']['is_package_slip_notes']) {
				$isPackageSlipNotes = true;
				$packageSlipNotes = $orderSetting['package_slip']['package_slip_notes']
				? $orderSetting['package_slip']['package_slip_notes'] : '';
				$packageSlipNotes = str_replace('  ', ' &nbsp;', nl2br(htmlentities($packageSlipNotes)));
			}
			$pakageSlipAddress = $orderSetting['package_slip']['package_slip_address']
			? $orderSetting['package_slip']['package_slip_address'] : '';
			$pakageSlipAddress = str_replace('  ', ' &nbsp;', nl2br(htmlentities($pakageSlipAddress)));
			$isProductImage = $orderSetting['package_slip']['is_package_slip_image_inlude']
			? true : false;
			$packageSlipStoreUrl = $orderSetting['package_slip']['package_slip_url']
			? $orderSetting['package_slip']['package_slip_url'] : '';
		}

		if (!empty($args) && $orderId && !empty($orderSetting)) {
			/** get font for default language */
			$languageFont =  $this->getDefaultLanguageFont($storeId, "admin");
			if ($getLanguage['name'] == "Japanese" || $getLanguage['name'] == "Chinese") {
				$fontFamily = "simsun";
				$fontAll = "simsun";
				$fontUrl = "";
			} else {
				$fontFamily = "DejaVuSans";
				$fontAll = "DejaVuSans";
				$fontUrl = "";
			}
			$fontStyle = $languageFont['font_style'];
			$fontWeight = $languageFont['font_weight'];
			$trueType = $languageFont['true_type'];
			$args['is_return'] = true;
			$order = $this->getOrderDetails($request, $response, $args);
			if (!empty($order) && $order['order_details']) {
				$barcodeImageSrc = $barCodeImageUrl;
				$orderDetails = $order['order_details'];
				$createDate = $orderDetails['created_date'];
				$orderDate = date('jS F, Y', strtotime($createDate));
				$storeUrl = $packageSlipStoreUrl ? $packageSlipStoreUrl : $orderDetails['store_url'];
				$html = '<html>
					<head><title>' . $pdfLanguage['package-slip'] . '</title>
					<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
					<style>@media print {
					        body {-webkit-print-color-adjust: exact;}
					    }
					    @font-face {
							font-family: "' . $fontFamily . '";
							font-style: ' . $fontStyle . ';
							font-weight: ' . $fontWeight . ';
							src: url(' . $fontUrl . ') format("' . $trueType . '");
	                    }
	                    * {
							font-family: ' . $fontAll . ';
					    }
					</style></head><body>

					<table width="100%" cellpadding="0" cellspacing="0" border="0" style="font-family: '.$fontAll.';">
					    <tbody>
					        <tr>
					            <td>
					                <table width="100%" cellpadding="0" cellspacing="0" border="0">
					                    <tbody>
					                        <tr>
					                            <td width="50%"><br/>
					                                <span><img src="' . $packingSlipLogo . '" width="100px"></span><br/>
					                                <span style="font-size:14px; margin: 10px 0 8px 0;">' . $pakageSlipAddress . '</span><br/>
					                                <span style="font-size:14px; margin: 0px 0 0px 0;">' . $storeUrl . '</span><br/>
					                            </td>
					                            <td width="50%" align="'.$rtlLeftAlign.'">
					                                <span style="font-size: 22px;font-weight:bold;">' . $pdfLanguage['package-slip'] . '</span><br/>
					                                <span style="font-size:14px; margin: 0 0 5px 0;"><b>' . $pdfLanguage['id'] . ' :</b> #' . $orderDetails['id'] . '</span><br/>
					                                <span style="font-size:14px; margin: 0 0 5px 0;"><b>' . $pdfLanguage['date'] . ' :</b> ' . $orderDate . '</span><br/>
					                                <span style="font-size:14px; margin: 0 0 0px 0;"><b>' . $pdfLanguage['payment-mode'] . ' :</b> ' . $orderDetails['payment'] . '</span><br/>
					                                <img src="' . $barcodeImageSrc . '" style="height:100%; max-height:25px; margin-top: 20px;">
					                            </td>
					                        </tr>
					                    </tbody>
					                </table>
					            </td>
					        </tr>
					        <tr>
					            <td>
					                <hr style="margin: 30px 0 0 0;">
					            </td>
					        </tr>
					        <tr>
					            <td>
					                <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin: 20px 0 0 0;">
					                    <tbody>
					                        <tr>
					                            <td width="50%" align="'.$rtlRightAlign.'">
					                            	<br/>
					                                <span style="padding: 0; margin: 0 0 10px 0; font-size: 18px;font-weight:bold;">' . $pdfLanguage['bill-to'] . '</span><br/>
					                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['billing']['first_name'] . ' ' . $orderDetails['billing']['last_name'] . '</span><br/>
					                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['billing']['address_1'] . ' ' . $orderDetails['billing']['address_2'] . '</span><br/>
					                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['billing']['city'] . ', ' . $orderDetails['billing']['state'] . ', ' . $orderDetails['billing']['postcode'] . ',' . $orderDetails['billing']['phone'] . '</span><br/>
					                            </td>
					                            <td width="50%" align="'.$rtlLeftAlign.'">
					                                <span style="padding: 0; margin: 0 0 10px 0; font-size: 18px;font-weight:bold;">' . $pdfLanguage['ship-to'] . '</span><br/>
					                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['shipping']['first_name'] . ' ' . $orderDetails['shipping']['last_name'] . '</span><br/>
					                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['shipping']['address_1'] . ' ' . $orderDetails['shipping']['address_2'] . '</span><br/>
					                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['shipping']['city'] . ', ' . $orderDetails['shipping']['state'] . ', ' . $orderDetails['shipping']['postcode'] . ',' . $orderDetails['shipping']['phone'] . '</span><br/>
					                            </td>
					                        </tr>
					                    </tbody>
					                </table>
					            </td>
					        </tr>
					        <tr>
					        	<td>
						            <table width="100%" cellpadding="5" cellspacing="0" border="0" style="font-size:14px; margin: 30px 0 0 0;">
						                <thead>
						                    <tr>
						                      	<td width="8%" style="text-align: '.$rtlRightAlign.'; padding: 10px; background: #e3e4e6; border: 1px solid #aaa;font-weight:bold;">' . $pdfLanguage['no'] . '</td>';
												if ($isProductImage) {
													$html .= '<td width="42%" style="text-align: '.$rtlRightAlign.'; padding: 10px; background: #e3e4e6; border: 1px solid #aaa;font-weight:bold;">' . $pdfLanguage['item'] . '</td>';
												}
												$html .= '<td width="35%" style="text-align: '.$rtlRightAlign.'; padding: 10px; background: #e3e4e6; border: 1px solid #aaa;font-weight:bold;">' . $pdfLanguage['product'] . '</td>
						                      	<td width="15%" style="text-align: '.$rtlRightAlign.'; padding: 10px; background: #e3e4e6; border: 1px solid #aaa;font-weight:bold;">' . $pdfLanguage['quantity'] . '</td>
						                    </tr>
						                  </thead>
						                <tbody>';
										foreach ($orderDetails['orders'] as $k => $item) {
											$no = $k + 1;
											$html .= '<tr>
								                        <td style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">
								                            ' . $no . '
								                        </td>';
											if ($isProductImage) {
												$html .= '<td style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">';
												foreach ($item['images'] as $images) {
													$html .= '<img src="' . $images['thumbnail'] . '" style="width:30px; height:30px; margin:0 5px 0 0">';
												}
												$html .= '</td>';
											}
											$html .= '<td style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">' . $item['name'] . '
								                        </td>
								                        <td style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;">
								                            ' . $item['quantity'] . '
								                        </td>
								                    </tr>';
										}

							$html .= '</tbody></table></td></tr>';
							if ($isPackageSlipNotes) {
								$html .= '<br/>
								<tr>
						            <td width="100%" align="'.$rtlRightAlign.'" style="text-align: '.$rtlRightAlign.';">
						                <table width="100%" cellpadding="0" cellspacing="0" border="0" style="font-size:14px; margin: 30px 0 0 0;">
					                        <tr>
					                            <td>
					                                <br/><span style="font-size: 20px; font-family: ' . $fontAll . '">' . $pdfLanguage['note'] . '</span><br/>
					                				<span style="line-height:24px; font-size:14px; padding: 0; font-family: ' . $fontAll . '"> ' . $packageSlipNotes . '</span>
					                            </td>
					                        </tr>
					                    </table>
						            </td>
								</tr>';
							}
				$html .= '</tbody></table></body></html>';
				$orderPath = path('abs', 'order');
				$orderIdPath = $orderPath . $orderId . '/';
				$fileName = create_tcpdf($html, $orderIdPath, '', $lang=$getLanguage['name']);
				$dir = $orderIdPath . $fileName;
				//Download file in local system
				if (file_download($dir)) {
					$serverStatusCode = OPERATION_OKAY;
					$jsonResponse = [
						'status' => 1,
					];
				}
			}
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Order seeting packing slip logo
	 *
	 * @author radhanatham@riaxe.com
	 * @date   28 May 2020
	 * @return String
	 */
	private function getPackingSlipLogo($storeId) {
		$packingSlipLogo = '';
		$orderSettingPath = path('abs', 'setting') . 'order_setting';
		if (is_dir($orderSettingPath)) {
			$orderSettingPath = $orderSettingPath . '/' . $storeId;
			$scanDir = scandir($orderSettingPath);
			if (is_array($scanDir)) {
				foreach ($scanDir as $dir) {
					if ($dir != '.' && $dir != '..' && (strpos($dir, "thumb_") === false)) {
						$packingSlipLogo = path('read', 'setting') . 'order_setting/' . $storeId . '/' . $dir;
					}
				}
			}
		}
		return $packingSlipLogo;
	}
	/**
	 * GET : Get all order status
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soumyas@riaxe.com
	 * @date   03 June 2020
	 * @return json response wheather data is updated or not
	 */
	public function getAllOrderStatus($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Order Status ', 'error')
		];
		$maxCacheTime = 12 * 3600; // 12 hours
		$orderStatusesData = [];
		$getStoreDetails = get_store_details($request);
		// cache file
		$orderStatusCacheContent = ORDER_STATUS_CACHE_FOLDER . "order_status.json";
		// getting the last updated/created time of the cache
		if (file_exists($orderStatusCacheContent) && ((time() - filemtime($orderStatusCacheContent)) <= $maxCacheTime)) {
			$orderStatusInfo = file_get_contents($orderStatusCacheContent, true);
			$orderStatusesData = json_decode($orderStatusInfo, true);
		} else {
			// update the cache data
			mkdir(ORDER_STATUS_CACHE_FOLDER);
			$orderStatusesData = $this->getDefaultOrderStatuses($getStoreDetails['store_id']);
			file_put_contents($orderStatusCacheContent, json_encode($orderStatusesData));
		}
		if (isset($args['return_type']) && $args['return_type'] == 1) {
			return $orderStatusesData;
		}
		if ($orderStatusesData) {
			$jsonResponse = [
				'status' => 1,
				'data' => $orderStatusesData
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
	/**
	 * POST : Update order status
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soumyas@riaxe.com
	 * @date   03 June 2020
	 * @return json response wheather data is updated or not
	 */
	public function updateOrderStatus($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Update Order Status ', 'error'),
		];
		if (isset($args) && !empty($args)) {
			$orderId = $args['id'];
			$updateData = $request->getParsedBody();
			$date = date_time(
                'today', [], 'string'
            );
			$newStatus = isset($updateData['new_status']) ? $updateData['new_status'] : '';
			$oldStatus = isset($updateData['old_status']) ? $updateData['old_status'] : '';
			unset($updateData['new_status'], $updateData['old_status']);
			$storeDetails = get_store_details($request);
			$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
			if (!empty($updateData)) {
				$this->updateCatalogOrderStatus($orderId, $updateData, $storeId);
				$updateResponse = $this->updateStoreOrderStatus($orderId, $updateData, $storeId);
				if ((isset($updateResponse['id']) && $updateResponse['id'] > 0) || $updateResponse == 'success') {
					$orderLogData = [
						'order_id' => $orderId,
						'agent_type' => 'admin',
						'agent_id' => 1,
						'store_id' => $storeId,
						'message' => 'Status changed from '.$oldStatus.' to '.$newStatus.'.',
						'log_type' => 'Status changed',
						'status' => 'new',
						'created_at' => $date
					];
					$saveOrderLog = new OrderLog($orderLogData);
					$saveOrderLog->save();
					$jsonResponse = [
						'status' => 1,
						'message' => 'Order status updated successfully',
					];
				} else {
					$jsonResponse = [
						'status' => 0,
						'message' => 'Order status not updated',
					];
				}

			} else {
				$jsonResponse = [
					'status' => 0,
					'message' => 'Order status empty',
				];
			}

		} else {
			$jsonResponse = [
				'status' => 0,
				'message' => 'Order id empty',
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
	/**
	 * POST : Artwork send to vendor
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soumyas@riaxe.com
	 * @date   04 June 2020
	 * @return json response wheather data is updated or not
	 */
	public function sendToPrintShop($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Save order token ', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$fromEmail = $allPostPutVars['fromEmail'] ? $allPostPutVars['fromEmail'] : '';
		$printShopEmail = $allPostPutVars['printShopEmail'] ? $allPostPutVars['printShopEmail'] : '';
		$customerEmail = $allPostPutVars['customerEmail'];
		$orderId = $allPostPutVars['orderId'];
		$subject = $allPostPutVars['subject'] ? $allPostPutVars['subject'] : '';
		$message = $allPostPutVars['description'] ? $allPostPutVars['description'] : '';
		$fromOrderStatus = $allPostPutVars['from_order_status'] ? $allPostPutVars['from_order_status'] : 0;
		$orderStatus = $allPostPutVars['order_status'] ? $allPostPutVars['order_status'] : '';
		
		// $moduleId = 2; /* Order module  */
		$getStoreDetails = get_store_details($request);
		if (!empty($customerEmail) && !empty($orderId)) {
			$type = 1; /*For general setting*/
			$settingsInit = new \App\Modules\Settings\Models\Setting();
			$getSettings = $settingsInit->where([
				'type'=>$type, 
				'store_id'=> $getStoreDetails['store_id'] ? $getStoreDetails['store_id']:1  
			]);
			if ($getSettings->count() > 0)  {
				$smtpEmailSettingData = $getSettings->get()->toArray();
				$smtpId = array_search('smtp_details', array_column($smtpEmailSettingData, 'setting_key')); 
				$emailAddressId = array_search('email_address_details', array_column($smtpEmailSettingData, 'setting_key')); 
				$emailAddressInfo = $smtpEmailSettingData[$emailAddressId];
				$emailData = json_clean_decode($emailAddressInfo['setting_value'], true);
				$smtpInfo = $smtpEmailSettingData[$smtpId];
				$smtpData = json_clean_decode($smtpInfo['setting_value'], true);
			}
			$replyToEmail = '';
			$attachments = [];
			$fromName = $emailData['from_email'];
			$fromEmail = $smtpData['smtp_from'];
			$smtpData['smtp_pass'] =  $this->decryptKey($smtpData['smtp_pass']);
			$mailContaint = ['from' => ['email' => $fromEmail, 'name' => $fromName],
				'recipients' => [
					'to' => [
						'email' => $printShopEmail,
						'name' => '',
					],
					'reply_to' => [
						'email' => $replyToEmail,
						'name' => $replyToEmail,
					],
				],
				'attachments' => ($attachments != '') ? $attachments : [],
				'subject' => $subject,
				'body' => $message,
				'smptData' => $smtpData,
			];
			if ($smtpData['smtp_host'] != '' && $smtpData['smtp_user'] != '' && $smtpData['smtp_pass'] != '') {
				$mailResponse = email($mailContaint);
			} else {
				$mailResponse['status'] = 0;
			}
			if (!empty($mailResponse['status']) && $mailResponse['status'] == 1) {
				if ($fromOrderStatus == 1 && $orderStatus != '') {
					$date = date_time(
		                'today', [], 'string'
		            );
					$orderLogData = [
						'order_id' => $orderId,
						'agent_type' => 'admin',
						'agent_id' => 1,
						'store_id' => $getStoreDetails['store_id'] ? $getStoreDetails['store_id']:1,
						'message' => 'Email is sent to customer for changing the status to '.$orderStatus,
						'log_type' => 'Email notify',
						'status' => 'new',
						'created_at' => $date
					];
					$saveOrderLog = new OrderLog($orderLogData);
					$saveOrderLog->save();
				}
				$jsonResponse = [
					'status' => 1,
					'message' => 'Email sent successfully ',
				];
			} else {
				$jsonResponse = [
					'status' => 0,
					'message' => 'Email can not send',
				];
			}
		} else {
			$jsonResponse = [
				'status' => 0,
				'message' => 'Customer email empty',
			];
		}

		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}
	/**
	 * POST : Archive Orders
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author satyabratap@riaxe.com
	 * @date   19 July 2020
	 * @return json response wheather product is updated or not
	 */
	public function archiveOrders($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Archile Orders', 'error'),
		];
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
		$storeResponse = $this->archiveOrderById($request, $response, $args);
		$updateData['statusKey'] = 'completed';
		$orderIds = $request->getParsedBody();
		$orderIDs = explode (",", str_replace(array( '[', ']' ), '', $orderIds['order_id']));
		foreach($orderIDs as $orderValue){
			$this->updateCatalogOrderStatus($orderValue, $updateData, $storeId);
        }
		if ($storeResponse['status'] == 1) {
			$jsonResponse = [
				'status' => 1,
				'message' => message('Archile Orders', 'done'),
			];
		}

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

	/**
	 * POST : Convert to order
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soumyas@riaxe.com
	 * @date   27 May 2020
	 * @return json response wheather data is updated or not
	 */
	public function convertToOrder($request, $response, $args) {
		$allPostPutVars = $request->getParsedBody();
		$fetchData = $allPostPutVars['data'];
		$decodeData = json_clean_decode($fetchData, true);
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Order Status ', 'error'),
		];
		if (!empty($decodeData)) {
			if ($decodeData['quote_id'] && $decodeData['customer_id']) {
				$storeResponseOrder = $this->storeOrder($decodeData);
				if (!empty($storeResponseOrder)) {
					if ($storeResponseOrder['id'] > 0) {
						$jsonResponse = [
							'status' => 1,
							'data' => $storeResponseOrder['id'],
							'order_number' => (isset($storeResponseOrder['order_number']) && $storeResponseOrder['order_number'] != '') ? $storeResponseOrder['order_number'] : $storeResponseOrder['id'],
							'message' => 'Order placed successfully',
						];

					} else {
						$jsonResponse = [
							'status' => 0,
							'message' => 'Order placed error',
						];
					}

				} else {
					$jsonResponse = [
						'status' => 0,
						'message' => 'Order not created',
					];
				}
			} else {
				$jsonResponse = [
					'status' => 0,
					'message' => 'Quote id / Customer id  are empty ',
				];
			}
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET: Store Items Details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Args object
	 *
	 * @author debashrib@riaxe.com
	 * @date   12 July 2020
	 * @return array json
	 */
	public function getStoreItemsDetails($request, $response, $args, $returnType = 0) {
		$serverStatusCode = OPERATION_OKAY;

		//GET MEMCACHEDATA
		$memcacheData = [];
		$ui= 1;
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'];
		$orderId = $args['id'];
		$isPurchaseOrder = isset($args['is_purchase_order']) ? $args['is_purchase_order'] : 0 ; 
		if (IS_MEMCACHE) {
			//MEMCACHED KEY
			 $thisCacheKey = "orders" . "_id" . $orderId . "_PO" . $isPurchaseOrder."_store". $storeId;
			//Register MEMCACHED KEY in Local Cache
			$this->createUpdateMemCacheGroup('orders', $thisCacheKey, 'SET');
			$memcacheData = $this->memcache("get", $thisCacheKey);
		}
		if(empty($memcacheData)){
			$orderDetails = $this->orderItemDetails($request, $response, $args);
			$this->memcache("set", $thisCacheKey, $orderDetails);
		}else{
			$orderDetails = $memcacheData;
			if (MEM_MODE) {
                $orderDetails['mode'] = 'memcache';
            }
		}
		if ($returnType == 1) {
			return $orderDetails;
		}

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

	/**
	 * GET: Generate Work Order Slip
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Args object
	 *
	 * @author debashrib@riaxe.com
	 * @date   07 Sept 2020
	 * @return array json
	 */
	public function downloadWorkOrderSlip($request, $response, $args) 
	{
		ini_set('memory_limit', '2G');
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Work Order Slip Download', 'error'),
		];
		
		$showPrice = $request->getQueryParam('show_price') ? $request->getQueryParam('show_price') : 0;
		$storeId = $request->getQueryParam('store_id') ? $request->getQueryParam('store_id') : 1;
		$orderId = $args['id'];
		if (!empty($args) && $orderId && $orderId > 0) {
			/** get font for default language */
			$languageFont =  $this->getDefaultLanguageFont($storeId, "admin");
			// Fetch language Type
			$languageInit = new Language();
			$where = ['type' => 'admin', 'is_default' => 1, 'store_id'=> $storeId];
	        $getLanguage = $languageInit->where($where)->first()->toArray();
	        // End
			if ($getLanguage['name'] == "Japanese" || $getLanguage['name'] == "Chinese") {
				$fontFamily = "simsun";
				$fontAll = "simsun";
				$fontUrl = "";
			} else {
				$fontFamily = "DejaVuSans";
				$fontAll = "DejaVuSans";
				$fontUrl = "";
			}
			$fontStyle = $languageFont['font_style'];
			$fontWeight = $languageFont['font_weight'];
			$trueType = $languageFont['true_type'];
			$class = (isset($languageFont['style']) && $languageFont['style']) == 'rtl' ? 'rtl' : '';
			$args['is_return'] = true;
			$pdfLanguage = $this->languageContent['order-pdf'];
			//Get order Details 
			$order = $this->getOrderDetails($request, $response, $args);
			$barCodeImageUrl =  ASSETS_PATH_R.'bar_codes/order-'.$orderId.'.png';
	        $rtlLeftAlign = "right";
	        $rtlRightAlign = "left";
	 		if ($getLanguage['name'] == 'Arabic') {
	 			$rtlLeftAlign = "left";
	        	$rtlRightAlign = "right";
	 		}

			if (!empty($order) && $order['order_details']) {
				$orderDetails = $order['order_details'];
				$html = '<!doctype html>
	            <html lang="en-US">

	            <head>
	                <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	                <style>
                    @font-face {
						font-family: "'.$fontFamily.'";
						font-style: '.$fontStyle.';
						font-weight: '.$fontWeight.';
						src: url('.$fontUrl.') format("'.$trueType.'");
                    }
                    * {
						font-family: '.$fontAll.';
				    }
					h3 {
			            font-family: "'.$fontFamily.'";
                      	font-style: '.$fontStyle.';
                      	font-weight: '.$fontWeight.';
                      	src: url('.$fontUrl.') format("'.$trueType.'");
        			}
        			p {
			            font-family: "'.$fontFamily.'";
                      	font-style: '.$fontStyle.';
                      	font-weight: '.$fontWeight.';
                      	src: url('.$fontUrl.') format("'.$trueType.'");
        			}
        			h4 {
			            font-family: "'.$fontFamily.'";
                      	font-style: '.$fontStyle.';
                      	font-weight: '.$fontWeight.';
                      	src: url('.$fontUrl.') format("'.$trueType.'");
        			}
                  </style>
	            </head>
				<body style="margin: 0; padding: 0;">
                <table cellpadding="5">
                <table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%;">
              		<tr>
                		<td width="60%" style="vertical-align: top;"><br/>
                  			<span style="font-size:22px;font-weight:bold;">'.$pdfLanguage['work-order-slip'].'</span><br/><br/>
                  			<table width="100%" cellspacing="0" cellpadding="0" border="0" style="font-size: 13px;">
                    			<tr>
                      				<td width="40%" style="padding: 0 20px 4px 0px;font-weight:bold;">'.$pdfLanguage['order-no'].'</td>
                      				<td width="60%" style="padding: 0 20px 4px 0px;">
                        				: <span>#' . $orderDetails['order_number'] . '</span>
                      				</td>
                    			</tr>
                    			<tr>
                      				<td width="40%" style="padding: 0 20px 4px 0px;font-weight:bold;">'.$pdfLanguage['purchase-date'].'</td>
                      				<td width="60%" style="padding: 0 20px 4px 0px;">
                        				: <span>' . date("M d,Y h:i a", strtotime($orderDetails['created_date'])) . '</span>
                      				</td>
                    			</tr><br/>
								<tr>
			                    	<td colspan="2" width="100%">
			                    		<img src="'.$barCodeImageUrl.'" style="height:25px; width: auto; max-height:25px; margin-top:8px;"/>
			                    	</td>
			                    </tr>
                  			</table>
                		</td>
                		<td width="40%" align="'.$rtlLeftAlign.'" style="vertical-align: top; font-size: 14px;">';
                			$html .= '<span style="font-size: 14px; line-height: 22px;">
		                    ' . $orderDetails['customer_first_name'] . ' ' . $orderDetails['customer_last_name'] . '<br/>
		                    ' . $orderDetails['customer_email'] . '<br/>
		                    ' . $orderDetails['billing']['phone'] . '
                  			</span>
                		</td>
              		</tr>
              		<tr>
						<td colspan="2" width="100%">
							<hr style="margin: 30px 0 0 0;">
						</td>
              		</tr>
            	</table>
            	<table width="100%" cellspacing="0" cellpadding="0" border="0" style="min-width: 100%; margin-bottom: 30px;">
              		<tr>
		                <td width="50%" style="vertical-align: top; font-size: 14px; line-height: 22px;">
		                <br/>
		                  <strong style="font-size: 18px;">'.$pdfLanguage['bill-addr'].'</strong>';
		                  if ($orderDetails['billing']['address_1'] != '') {
			                  $html .= '<span><br/>
			                    ' . $orderDetails['billing']['address_1'] . ', ' . $orderDetails['billing']['address_2'] . '<br/>
			                    ' . $orderDetails['billing']['city'] . ', ' . $orderDetails['billing']['state'] . '<br/>
			                    ' . $orderDetails['billing']['country'] . '-' . $orderDetails['billing']['postcode']
			                  .'</span>';
			              }
		                $html .= '</td>
		                <td align="'.$rtlLeftAlign.'" width="50%" style="vertical-align: top; font-size: 14px; line-height: 22px;">
		                <br/>
		                  <strong style="font-size: 18px;">'.$pdfLanguage['ship-addr'].'</strong>';
						if ($orderDetails['shipping']['address_1'] != '') {
							$html .= '<span><br/>
		                    ' . $orderDetails['shipping']['address_1'] . ', ' . $orderDetails['shipping']['address_2'] . '<br/>
		                    ' . $orderDetails['shipping']['city'] . ', ' . $orderDetails['shipping']['state'] . '<br/>
		                    ' . $orderDetails['shipping']['country'] . '-' . $orderDetails['shipping']['postcode'] . '
		                  </span>';
						}
						$display = ($orderDetails['note'] == '') ? 'display: none;' : '';
						$html .= '</td>
              		</tr>
            	</table>';
	            if ($showPrice == 1) {
		            $html .= '<table width="100%" cellpadding="5" cellspacing="0" border="0" style="font-size: 14px; line-height: 24px;">
		              	<thead>
			                <tr>
			                	<th align="center" width="10%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;"> 
			                    '.$pdfLanguage['sl-no'].'
			                  </th>
			                  <th align="center" width="40%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;"> 
			                    '.$pdfLanguage['product-name'].'
			                  </th>
			                  <th align="center" width="15%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;"> 
			                    '.$pdfLanguage['unit-price'].'
			                  </th>
			                  <th align="center" width="15%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;"> 
			                    '.$pdfLanguage['total-qty'].'
			                  </th>
			                  <th align="center" width="20%" bgcolor="#e3e4e6" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;"> 
			                    '.$pdfLanguage['total-price'].'
			                  </th>
			                </tr>
		              	</thead>
		              	<tbody>';
		                $subtotal = 0;
		                $customArr = [];
		                foreach ($orderDetails['orders'] as $orderKey => $orders) {
		                	if (!array_key_exists($orders['custom_design_id'],$customArr)) {
		                		$customArr[$orders['custom_design_id']] = $orderKey;
							}
		                    $slNo = $orderKey + 1;
		                    $background = (($slNo % 2) == 0) ? 'background-color: rgba(0, 0, 0, 0.05);' : '';
		                    $subtotal = $subtotal + $orders['total'];
		                    $html .= '<tr>
		                  	<td valign="top" width="10%" style="text-align: center; padding: 10px; border: 1px solid #aaa;"> ' . $slNo . '</td>
		                  	<td valign="top" width="40%" style="text-align: center; padding: 10px; border: 1px solid #aaa;"><b> ' . $orders['name'] .'</b> '.$orders['sku']. '</td>
		                  	<td valign="top" width="15%" style="text-align: center; padding: 10px; border: 1px solid #aaa;"> ' . number_format($orders['price'], 2) . ' ' . $orderDetails['currency'] . '</td>
		                  	<td valign="top" width="15%" style="text-align: center; padding: 10px; border: 1px solid #aaa;"> ' . $orders['quantity'] . '</td>
		                  	<td valign="top" width="20%" style="text-align: center; padding: 10px; border: 1px solid #aaa;"> ' . number_format($orders['total'], 2) . ' ' . $orderDetails['currency'] . '</td>
		                	</tr>';
		                }
		                $totalAmount = ($orderDetails['total_amount'] + $orderDetails['total_shipping'] + $orderDetails['total_tax']) - $orderDetails['total_discounts'];
		                $html .= '</tbody>
		            </table>';
	        	}
	            $display = (empty($orderDetails['notes']))? 'display: none;' : '';
	            $html .= '<table width="100%" cellspacing="0" cellpadding="0" border="0" style="margin-top: 30px;">
	              	<tr>
	                	<td width="50%">
	                  		<br/><span style="font-size: 16px;font-weight:bold; ' . $display . '">'.$pdfLanguage['notes'].'</span><br/>';
			                  	if (!empty($orderDetails['notes'])) {
				                  	foreach ($orderDetails['notes'] as $notes) {
					                  $html .= '<span style="font-size: 14px; line-height: 22px;">
					                    ' . $notes . '
					                  </span>';
					              	}
			          			}
	                	$html .= '</td>';
		                if ($showPrice == 1) {
			                $html .= '<td width="50%" align="'.$rtlLeftAlign.'"><br/>
			                  	<table width="100%" cellspacing="0" cellpadding="5" border="0" style="font-size: 14px;">
			                    	<tr>
			                      		<td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['subtotal'].'</td>
			                      		<td width="40%" style="text-align: center; padding: 6px 10px; border: 1px solid #aaa;"> ' . number_format($orderDetails['total_amount'], 2) . ' ' . $orderDetails['currency'] . '</td>
			                    	</tr>';
				                    if ($orderDetails['total_discounts'] > 0) {
						                $html .= '<tr>
					                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['discount'].'</td>
					                      <td width="40%" style="text-align: center; padding: 6px 10px; border: 1px solid #aaa;"> -' . number_format($orderDetails['total_discounts'], 2) . ' ' . $orderDetails['currency'] . '</td>
					                    </tr>';
					                }
					                if ($orderDetails['total_shipping'] > 0) {
					                    $html .= '<tr>
					                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['shipping'].'</td>
					                      <td width="40%" style="text-align: center; padding: 6px 10px; border: 1px solid #aaa;"> ' . number_format($orderDetails['total_shipping'], 2) . ' ' . $orderDetails['currency'] . '</td>
					                    </tr>';
					                }
				                    if ($orderDetails['total_tax'] > 0) {
						                $html .= '<tr>
					                      <td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['tax'].'</td>
					                      <td width="40%" style="text-align: center; padding: 6px 10px; border: 1px solid #aaa;"> ' . number_format($orderDetails['total_tax'], 2) . ' ' . $orderDetails['currency'] . '</td>
					                    </tr>';
					                }
		                    		$html .= '<tr>
										<td width="60%" style="text-align: '.$rtlRightAlign.'; padding: 6px 10px; border: 1px solid #aaa;font-weight:bold;"> '.$pdfLanguage['total'].'</td>
				                      	<td width="40%" style="text-align: center; padding: 6px 10px; border: 1px solid #aaa;">
				                        	 ' . number_format($totalAmount, 2) . ' ' . $orderDetails['currency'] . '
				                      	</td>
			                    	</tr>
			                  	</table>
			                  	<span style="font-size: 12px;">
			                    	('.$pdfLanguage['all-prices'].' ' . $orderDetails['currency'] . ')
			                  	</span>
			                </td>';
		            	}
		            $html .= '</tr>
	            </table>';
	            $html .= '<div style="page-break-before: always;"></div>';
				foreach ($orderDetails['orders'] as $orderKey => $orders) {
					$customOrderKey = $customArr[$orders['custom_design_id']];
					$slNo = $orderKey + 1;
					$html .= '<table width="100%" cellspacing="0" cellpadding="0" border="0">
		            	<tr>
			                <td colspan="2"><br/>
			                  <span style="text-align: '.$rtlRightAlign.'; font-size: 16px;"><strong>'.$pdfLanguage['order-item'].' ' . $slNo . '</strong></span>
			                </td>
		              	</tr>
	          			<tr>
	            			<td style="vertical-align: top;" width="20%">
								<table width="100%" cellspacing="0" cellpadding="0" border="0">
				                    <tr>
				                      <td style="padding: 5px;">
				                        <span style="width: 100px; margin: 0;">
				                          <img src="' . $orders['store_image'][0]['thumbnail'] . '" style="width : auto; hight: 150px;" alt=""/>
				                        </span>
				                      </td>
				                    </tr>
				                </table>
	            			</td>
	            			<td style="vertical-align: top; padding-left: 40px;" width="80%">
								<p style="font-size: 16px; margin-bottom: 20px;"><br/>
			                    	' . $orders['name'] . '<span>:<small> '.$orders['sku'].'</small></span>
			                  	</p><br/><br/>';
	              				$html .= '<table width="100%" cellspacing="0" cellpadding="5" style="font-size: 14px;">
	                 				<tr>
	                  					<td style="border: 1px solid #d3d3d3; background-color: #eee; text-align: center;">'.$pdfLanguage['quantity'].'</td>
	                  					<td style="padding: 6px 10px; border: 1px solid #e3e3e3;">
	                    					' . $orders['quantity'] . '
	                  					</td>
	                				</tr>';
				                    if ($showPrice == 1){
					                    $html .= '<tr>
					                      <td style="border: 1px solid #e3e3e3; background-color: #eee; text-align: center;">'.$pdfLanguage['price'].'</td>
					                      <td style="padding: 6px 10px; border: 1px solid #e3e3e3;">
					                        ' . number_format($orders['price'], 2) . ' ' . $orderDetails['currency'] . '
					                      </td>
					                    </tr>';
					                }
	              				$html .= '</table>
	              			</td>
	          			</tr>
	        		</table>';
	        		$html .= '<table width="100%" cellspacing="0" cellpadding="0">
	            		<tr>
	                		<td colspan="2">';
				            	if (!empty($orders['decoration_settings_data'])) {
				                	$html .= '<span style="text-align: '.$rtlRightAlign.'; font-size: 16px; margin-top: 20px;"><br/>
				                    <strong>'.$pdfLanguage['artwork-used'].'
				                  	</strong></span><br/><br/>';
				              	}
	                    		foreach ($orders['decoration_settings_data'] as $key => $decorationSettingsData) {
									$stickerInfo = $decorationSettingsData['stickerInfo'];
	                        		if (!empty($decorationSettingsData['decoration_data'])) {
	                            		$html .= '<table width="100%" cellspacing="0" cellpadding="0" style="border: 1px solid #e3e3e3;font-size: 14px;">
	                    					<tr>
	                      						<td style="padding: 12px;">';
						                            foreach ($decorationSettingsData['decoration_data'] as $decoKey => $decorationData) {
														// $pngUrl = $orderDetails['orders'][$customOrderKey]['decoration_settings_data'][$key]['decoration_data'][$decoKey]['png_url'];
														$svgUrl = $orderDetails['orders'][$customOrderKey]['decoration_settings_data'][$key]['decoration_data'][$decoKey]['svg_artwork_url'];
														$html .= '<table width="100%" cellspacing="0" cellpadding="0">
	                          								<tr>
									                            <td width="20%" style="vertical-align: top;">
										                            <span style="text-align: center; font-size:12px"><strong>'.$pdfLanguage['preview'].'</strong></span><br/>
										                            <span style="margin: 0; width: 150px; height: 150px;" >
										                            	<img src="' . $orders['images'][$key]['src'] . '" alt="" style="width: 150px; height: 150px;" />
										                            </span>
									                            </td>
									                            <td width="30%" style="vertical-align: top;">
									                            	<span style="text-align: '.$rtlRightAlign.'; font-size:12px"><strong>'.$pdfLanguage['design'].'</strong></span><br/>
									                              	<span style="margin: 0; width: 120px; height: 100px;">';
																	$html .= '<img src="' . $svgUrl . '" alt="" style="width: 150px; height: 150px;" /></span>';
																	if ($decorationData['design_width'] != '' && $decorationData['design_height'] != '') {
																		$html .= '<p style="font-size:12px;"><strong>' . $decorationData['design_width'] . ' X ' . $decorationData['design_height'] . ' (W X H) ' . $decorationData['print_unit'] . '</strong></p>';
																	}
																	
									                            $html .= '</td>
									                            <td width="50%" style="vertical-align: top;">
									                            	<table width="100%" cellspacing="0" cellpadding="5" border="0" style="font-size:12px">
										                                <tr>
																			<td style="padding: 0 0px 4px 20px;">'.$pdfLanguage['decoration-name'].'</td>
																			<td style="padding: 0 0px 4px 20px;"><strong>' . $decorationData['decoration_name'] . '</strong></td>
																		</tr>
									                                	<tr>';
											                                if ($decorationData['print_area_name'] != '') {
												                                $html .='<td style="padding: 0 0px 4px 20px;">'.$pdfLanguage['decoration-area'].'</td>
												                                  <td style="padding: 0 0px 4px 20px;"><strong>' . $decorationData['print_area_name'] . '</strong></td>
												                                </tr>';
											                                }
									                                	$html .='<tr>
									                                  		<td style="padding: 0 0px 4px 20px;">'.$pdfLanguage['print-method'].'</td>
									                                  		<td style="padding: 0 0px 4px 20px;"><strong>' . $decorationData['print_profile_name'] . '</strong></td>
									                                	</tr>
										                                <tr>
										                                	<td style="padding: 0 0px 4px 20px;">'.$pdfLanguage['width'].'</td>
										                                  	<td style="padding: 0 0px 4px 20px;"><strong>' . $decorationData['print_area_width'] . ' ' . $decorationData['print_unit'] . '</strong></td>
										                                </tr>
										                                <tr>
										                                	<td style="padding: 0 0px 4px 20px;">'.$pdfLanguage['height'].'</td>
										                                  	<td style="padding: 0 0px 4px 20px;"><strong>' . $decorationData['print_area_height'] . ' ' . $decorationData['print_unit'] . '</strong></td>
										                                </tr>';
										                                if (isset($decorationData['artwork_coordinates']) && !empty($decorationData['artwork_coordinates'])) {
											                                $html.='<tr>
											                                  <td style="padding: 0 0px 4px 20px;">'.$pdfLanguage['artwork-location'].'</td>
											                                  <td style="padding: 0 0px 4px 20px;"><strong>X: '.number_format($decorationData['artwork_coordinates']['x'], 2).', Y: '.number_format($decorationData['artwork_coordinates']['y'], 2). ' '. $decorationData['print_unit'].'</strong></td>
											                                </tr>';
											                            }
									                              	$html.='</table>
									                            </td>
									                        </tr>
									                    </table>';
	                            					}
													if(!empty($stickerInfo)) {
						                            	
						                            	$material = $pdfLanguage['material'] ? $pdfLanguage['material']:'Material';
						                            	$cutline = $pdfLanguage['cutline'] ? $pdfLanguage['cutline']:'Cutline';
						                            	$stickerOption = $pdfLanguage['sticker-option'] ? $pdfLanguage['sticker-option']:'Sticker Option';
						                            	$sheetInfo = '';
						                            	if ($stickerInfo['stickerOption'] == 'sheet') {
						                            		$sheetInfo = ' ('.$stickerInfo['sheetInfo'][$orderKey]['name'].')';
						                            	} else {
															if($stickerInfo['stickerOption'] == 'roll') {
																$sheetInfo = ' ('.$stickerInfo['rollInfo']['name'].')<br>
																<img src="'.$stickerInfo['rollInfo']['option']['file_name'].'" alt="" style="width: auto; height: 35px;"/>';
															}
														}
														
							                        	$html.='<table width="100%" cellspacing="0" cellpadding="5" border="0">';
							                        	$html.='<tr>';
							                        	$html.='<td style="vertical-align: top;">'.$material.' : '.$stickerInfo['material'].'</td>';
							                        	$html.='<td style="vertical-align: top;">'.$cutline.' : '.$stickerInfo['cutline'].'</td>';
							                        	$html.='<td style="vertical-align: top;">'.$stickerOption.' : '.ucfirst($stickerInfo['stickerOption']).$sheetInfo.'</td>';
							                        	
							                        	$html.='</tr>';
							                        	$html.='</table>';
						                        	}
	                            		$html .= '</td></tr></table>';
									}
								}

	                    	$html .= '</td>
	              		</tr>
	            	</table>';
	            }
				$html .= '</table></body></html>';
				$orderPath = path('abs', 'order');
				$orderIdPath = $orderPath . $orderId . '/';
				$fileName = create_tcpdf($html, $orderIdPath, $orderId, $getLanguage['name']);
				$dir = $orderIdPath . $fileName;
				//path('read', 'order') . $orderId . '/' . $fileName;
				//Download file in local system
				if (file_download($dir)) {
					$serverStatusCode = OPERATION_OKAY;
					$jsonResponse = [
						'status' => 1,
					];
				}
			}
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * POST : Order abbriviation values
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author soumyas@riaxe.com
	 * @date   04 June 2020
	 * @return json response wheather data is updated or not
	 */
	public function getOrderAbbriviationValues($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Save order token ', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$customerEmail = $allPostPutVars['customerEmail'];
		$orderId = $allPostPutVars['orderId'];
		$orderItemId = $allPostPutVars['orderItemId'];
		$showPrice = $allPostPutVars['showPrice'];
		$templateType = !empty($allPostPutVars['template_type']) ? $allPostPutVars['template_type'] : 'order_email_send';
		$responseData = [];
		$moduleId = 2; /* Order module  */
		$getStoreDetails = get_store_details($request) ? get_store_details($request) : 1;
		if (!empty($customerEmail) && !empty($orderId)) {
			/** get template data */
			$templateData = $this->getEmailTemplate($moduleId, $getStoreDetails, $templateType);
			//$templateData = json_clean_decode($templateData, true);
			if (!empty($templateData)) {
				if ($templateData[0]['is_configured'] == 1) {
					$abbrivationsInit = new ProductionAbbriviations();
					$getAbbrivations = $abbrivationsInit->where('module_id', $moduleId)->get();
					$abbriviationData = $getAbbrivations->toArray();
					$storeResponse = $this->getStoreOrders($request, $response, ['id' => $orderId, 'store_id' => $getStoreDetails['store_id']]);
					if (!empty($abbriviationData)) {
						foreach ($abbriviationData as $abbrData) {
							$abbrValue = $this->getAbbriviationValue($abbrData['abbr_name'], $storeResponse['order_details'], $showPrice, $orderItemId);
							$templateData[0]['message'] = str_replace($abbrData['abbr_name'], $abbrValue, $templateData[0]['message']);
							$templateData[0]['subject'] = str_replace($abbrData['abbr_name'], $abbrValue, $templateData[0]['subject']);
						}
						$responseData = $templateData[0];
					}
					$jsonResponse = [
						'status' => 1,
						'data' => $responseData,
						'is_template_exists' => 1,
					];
				} else {
					$jsonResponse = [
						'status' => 1,
						'message' => 'Order template empty',
						'is_template_exists' => 0,
					];
				}
			} else {
				$jsonResponse = [
					'status' => 1,
					'message' => 'Order template empty',
					'is_template_exists' => 0,
				];
			}
		} else {
			$jsonResponse = [
				'status' => 0,
				'message' => 'Customer email empty',
			];
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => $serverStatusCode
		]);
	}

	/**
	 * GET :Abbriviation values
	 *
	 * @param $orderId
	 * @param $orderItemId
	 * @param $customerEmailId
	 * @param $abbrName
	 *
	 * @author soumyas@riaxe.com
	 * @date   26 June 2020
	 * @return String
	 */
	public function getAbbriviationValue($abbrName, $getOrderDetails, $showPrice = 1, $orderItemId = '') {
		$abbrValue = '';
		$orderItems = $getOrderDetails['orders'];
		if ($abbrName == '{order_id}') {
			$abbrValue = '#'.ltrim($getOrderDetails['order_number'], "0");
		}
		if ($abbrName == '{product_name}') {
			$orderItemArr = array_filter($orderItems, function ($item) use ($orderItemId) {
	            return $item['id'] == $orderItemId;
	        });
	        $orderItemArr = $orderItemArr[array_keys($orderItemArr)[0]];
	        $customDesignId = $orderItemArr['custom_design_id'];
	        $productNameArr = [];
	        foreach ($orderItems as $item) {
	        	if ($item['custom_design_id'] == $customDesignId) {
	        		$productName = $item['name'] . ' SKU ' . $item['sku'];
	        		array_push($productNameArr, $productName);
	        	}
	        }
			$abbrValue = implode(', ', $productNameArr);
		}
		if ($abbrName == '{customer_name}' && !empty($getOrderDetails)) {
				$abbrValue = ($getOrderDetails['customer_first_name'] != '') ? $getOrderDetails['customer_first_name'] . " " . $getOrderDetails['customer_last_name'] . ',' : $getOrderDetails['customer_email'];
		}
		if ($abbrName == '{public_url}') {
			$this->deleteOrderTokenData($getOrderDetails['id'], $orderItemId);
			$artworkLink = '';
			$tokenData = "emailId=" . $getOrderDetails['customer_email'] . "&orderId=" . $getOrderDetails['id'] . "&orderItemId=" . $orderItemId. "&orderNumber=" . $getOrderDetails['order_number'];
			$token = base64_encode($tokenData);
			$saveData = array(
				'order_id' => $getOrderDetails['id'],
				'order_item_id' => $orderItemId,
				'token' => $token,
			);
			$orderItemTokenInit = new OrderItemToken($saveData);
			$status = $orderItemTokenInit->save();
			if ($status) {
				$artworkLink = BASE_URL . "download-artwork/" . $token;
			}
			$abbrValue = $artworkLink;
		}
		if ($abbrName == '{customer_address}') {
			$shippingAddress = $getOrderDetails['shipping'];
			if (!empty($shippingAddress)) {
				$customerName = $shippingAddress['first_name'] . ' ' . $shippingAddress['last_name'];
				$companyName = $shippingAddress['company'] ? $shippingAddress['company'] : '';
				$address_1 = $shippingAddress['address_1'] ? $shippingAddress['address_1'] : '';
				$city = $shippingAddress['city'] ? $shippingAddress['city'] : '';
				$state = $shippingAddress['state'] ? $shippingAddress['state'] : '';
				$country = $shippingAddress['country'] ? $shippingAddress['country'] : '';
				$postCode = $shippingAddress['postcode'] ? $shippingAddress['postcode'] : '';
				$abbrValue = $customerName . ' ' . $companyName . ' ' . $address_1 . ' ' . $city . '' . $state . ' ' . $postCode . ' ' . $country;
			}

		}
		if ($abbrName == '{order_status}') {
			$abbrValue = $getOrderDetails['status'];
		}
		if ($abbrName == '{artwork_status}') {
			$value = ['order_artwork_status'];
			$isArtworkEnabled = $this->getSettingStatus('artwork_approval', 6, $value);
			$ordersInit = new Orders();	
			$ordersArtworkStatus = $ordersInit->where('order_id', $getOrderDetails['id']);
			$artworkStatusData = $ordersArtworkStatus->first();
			$abbrValue = ($isArtworkEnabled == 1) ? $artworkStatusData->artwork_status: 'N/A';
		}
		if ($abbrName == '{order_created_date}') {
			$abbrValue = $getOrderDetails['created_date'];
		}
		if ($abbrName == '{order_value}' && $showPrice == 1) {
			$totalAmount = ($getOrderDetails['total_amount'] + $getOrderDetails['total_tax'] + $getOrderDetails['total_shipping']) - $getOrderDetails['total_discounts'];
			$abbrValue = $totalAmount . ' ' . $getOrderDetails['currency'];
		}
		if ($abbrName == '{payment_type}') {
			$abbrValue = $getOrderDetails['payment'];
		}
		if ($abbrName == '{order_notes}') {
			$abbrValue = $getOrderDetails['note'];
		}
		if ($abbrName == '{mobile_no}') {
			$abbrValue = $getOrderDetails['billing']['phone'];
		}
		if ($abbrName == '{customer_email}') {
			$abbrValue = $getOrderDetails['customer_email'];
		}
		return $abbrValue;
	}

	/**
	 *
	 * Delete token
	 * @param $orderId
	 * @param $orderItemId
	 * @author soumyas@riaxe.com
	 * @date   21 september 2020
	 * @return array
	 *
	 */
	public function deleteOrderTokenData($orderId, $orderItemId) {
		$tokenInit = new OrderItemToken();
		$tokenDelete = $tokenInit->where(
			['order_id' => $orderId, 'order_item_id' => $orderItemId]
		);
		return $tokenDelete->delete();
	}
	/**
	 * GET: Order line item po status
	 *
	 * @param $orderId
	 * @param $orderItemId
	 *
	 * @author soumyas@riaxe.com
	 * @date   12 October 2020
	 * @return
	 */
	public function getOrderPoStatus($orderId, $orderItemId, $storeId) {
		$poStatusArray = array();
		$purchaseOrderDetailsInit = new PurchaseOrderDetails();
		$getPurchaseOrder = $purchaseOrderDetailsInit->where(['order_id' => $orderId])->where(['order_item_id' => $orderItemId]);
		if ($getPurchaseOrder->count() > 0) {
			$purchaseStatusIds = $getPurchaseOrder->get()->toArray();
			if (!empty($purchaseStatusIds[0]['status_id'])) {
				$statusId = $purchaseStatusIds[0]['status_id'];
				
				$statusInit = new PurchaseOrderLineItemStatus();
				$statusArr = $statusInit
					->select('xe_id as id', 'store_id', 'status_name', 'color_code', 'is_default')
					->where(
						[
							'xe_id' => $statusId,
							'store_id' => $storeId,
						]
					)->orderBy('sort_order', 'ASC');
				if ($statusArr->count() > 0) {
					$statusData = $statusArr->get()->toArray();
					$poStatusArray = $statusData[0];
				}
			}
		}
		return $poStatusArray;
	}
	/**
	 * GET: Order po status
	 *
	 * @param $orderId
	 * @param $orderItemId
	 *
	 * @author soumyas@riaxe.com
	 * @date   12 October 2020
	 * @return
	 */
	public function getOrderPoStatusDetails($orderId, $poStatusId, $storeId)
	{
		$statusDetails = [];
		$statusIdArray = [];

		$statusInit = new PurchaseOrderLineItemStatus();
		$checkStatusReceived = false;
		$purchaseOrderDetailsInit = new PurchaseOrderDetails();
		$getPurchaseOrder = $purchaseOrderDetailsInit->where(['order_id' => $orderId]);
		if ($getPurchaseOrder->count() > 0) {
			$purchaseStatusIds = $getPurchaseOrder->get()->toArray();
			foreach ($purchaseStatusIds as $purchaseStatusId) {
				$statusId = $purchaseStatusId['status_id'];
				$statusIdArray[] = $statusId;
			}
			if (count(array_unique($statusIdArray)) === 1 && end($statusIdArray) === 3) {
				$checkStatusReceived = true;
			}
		}
		$selectQuery = $statusInit->select('xe_id as id', 'status_name', 'color_code', 'is_default')
		->where(['store_id' => $storeId]);

		if ($checkStatusReceived) {
			$statusArr = $selectQuery
				->where(
					[
						'xe_id' => $poStatusId
					]
				);
		} else {
			if (in_array(3, $statusIdArray)) {
				$partiallyReceived = 5;
				$statusArr = $selectQuery
					->where(
						[
							'xe_id' => $partiallyReceived
						]
					);
			} else {
				$createdStatusId = 4;
				$statusArr = $selectQuery
					->where(
						[
							'xe_id' => $createdStatusId
						]
					);
			}
		}

		if (isset($statusArr) && $statusArr->count() > 0) {
			$statusArr = $statusArr->orderBy('sort_order', 'ASC');
			$statusData = $statusArr->get()->toArray();
			$statusDetails = $statusData[0];
		}
		return $statusDetails;
	}

	/**
	 * Add data to orders table
	 *
	 * @param $orderId  Order id
	 * @param $$storeId Store id
	 * @param $customerId   Customer id
	 * @param $orderNumber   Order Number
	 *
	 * @author debashrib@riaxe.com
	 * @date   27 Oct 2020
	 * @return array json
	 */
	public function saveDataForOrder($orderId, $storeId, $customerId, $orderNumber = '') {
		$ordersInit = new Orders();
		$result = false;
		if ($orderId > 0 && $storeId > 0 && $customerId >= 0) {
			//check for order id
			$checkOrder = $ordersInit->where('order_id', $orderId);
			if ($checkOrder->count() == 0) {
				$saveOrderData = new Orders(
					[
						'order_id' => $orderId,
						'order_number' => $orderNumber,
						'artwork_status' => 'pending',
						'store_id' => $storeId,
						'customer_id' => $customerId,
					]
				);
				if ($saveOrderData->save()) {
					$result = true;
				}
			}
		}
		return $result;
	}

	/**
	 * Gte ordrer design data
	 *
	 * @param $orderResponse
	 *
	 * @author soumays@riaxe.com
	 * @date   18 Dec 2020
	 * @return array
	 */
	public function getOrderItemDesignData($orderResponse, $storeId) {
		$ordersInit = new Orders();
		$designId = $notes = [];
		foreach ($orderResponse as $orderDetailsKey => $orderDetails) {
			$designImages = [];
			$productDecoData = [];
			if (strtolower(STORE_NAME) == "shopify") {
				$getOrderFolderId = $orderDetails['order_number'];
			} else {
				$getOrderFolderId = $orderDetails['order_id'];
			}
			$isS3Enabled = $this->checkS3Settings($storeId);
			if ($orderDetails['custom_design_id'] > 0) {
				if ($isS3Enabled) {
					$orderIdPath = path('abs', 'order'). $getOrderFolderId;
					$this->downloadS3Content("/assets/orders/" . $getOrderFolderId, $orderIdPath, $storeId);
		            $jsonFileContent = json_decode(file_get_contents($orderIdPath . '/order.json'), true);
		        } else {
					$orderFolderDir = path('abs', 'order') . $getOrderFolderId . '/order.json';
					$jsonFile = read_file($orderFolderDir);
					$jsonFileContent = json_clean_decode($jsonFile, true);
				}
				//get the item key
				$jsonOrderItem = $jsonFileContent['order_details']['order_items'];
				$itemKey = array_search($orderDetails['item_id'], array_column($jsonOrderItem, 'item_id'));
				$customDesignId = $orderDetails['custom_design_id'];
				$deisgnStatePath = path('abs', 'design_state') . 'carts';
				$predecoPath = path('abs', 'design_state') . 'predecorators';
				$quotationPath = path('abs', 'design_state') . 'artworks';
				$orderJsonPath = $deisgnStatePath . '/' . $customDesignId . ".json";
				$orderPredecoPath = $predecoPath . '/' . $customDesignId . ".json";
				$orderQuotationPath = $quotationPath . '/' . $customDesignId . ".json";
				if (file_exists($orderJsonPath)) {
					$orderJson = read_file($orderJsonPath);
					$jsonContent = json_clean_decode($orderJson, true);
				} elseif (file_exists($orderPredecoPath)) {
					$orderJson = read_file($orderPredecoPath);
					$jsonContent = json_clean_decode($orderJson, true);
				} elseif (file_exists($orderQuotationPath)) {
					$orderJson = read_file($orderQuotationPath);
					$jsonContent = json_clean_decode($orderJson, true);
				}
				if (!empty($jsonContent['design_product_data'])) {
					$variantIdArr = [];
					foreach ($jsonContent['design_product_data'] as $designImage) {
						// Added for same product image for artwork
						if (file_exists($orderQuotationPath) || file_exists($orderPredecoPath)) {
							$designImages = [];
							if (!empty($designImage['design_urls'])) {
								foreach ($designImage['design_urls'] as $image) {
									$designImages[] = [
										'src' => $image,
										'thumbnail' => $image,
									];
								}
							}
						} else {
							if (($orderDetails['variant_id'] == 0 || in_array($orderDetails['variant_id'], $designImage['variant_id'])) &&
								!in_array($orderDetails['variant_id'], $variantIdArr)
							) {

								array_push($variantIdArr, $orderDetails['variant_id']);
								if (!empty($designImage['design_urls'])) {
									foreach ($designImage['design_urls'] as $image) {
										$designImages[] = [
											'src' => $image,
											'thumbnail' => $image,
										];
									}
								}
							}
						}
						$orderResponse[$orderDetailsKey]['variableDecorationSize'] = isset($designImage['variable_decoration_size']) ? $designImage['variable_decoration_size'] : '';
						$orderResponse[$orderDetailsKey]['variableDecorationUnit'] = isset($designImage['variable_decoration_unit']) ? $designImage['variable_decoration_unit'] : '';
					}
				}
				if (!empty($jsonContent['sides'])) {
					$i = 1;
					foreach ($jsonContent['sides'] as $sideDetails) {
						$configurator = [];
						if (isset($sideDetails['configurator']) && !empty($sideDetails['configurator'])) {
							$configurator = $sideDetails['configurator'];
						}
						$stickerInfo = [];
						if (isset($sideDetails['stickerInfo']) && !empty($sideDetails['stickerInfo'])) {
							$stickerInfo = $sideDetails['stickerInfo'];
						}
						$sideName = !empty($sideDetails['side_name']) ? $sideDetails['side_name'] : "";
						$isDesign = !empty($sideDetails['is_designed']) ? $sideDetails['is_designed'] : 0;
						$decorationData = [];
						if (!empty($sideDetails['print_area'])) {
							$j = 0;
							foreach ($sideDetails['print_area'] as $profile) {
								$digits = 3;
								$rvnUniqeNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
								$orderDwonloadObj = new OrderDownloadController();
								$svgPath = ASSETS_PATH_W . 'orders/' . $getOrderFolderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $getOrderFolderId . '.svg';
								$pngPath = ASSETS_PATH_W . 'orders/' . $getOrderFolderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $getOrderFolderId . '.png';
								$pngUrl = ASSETS_PATH_R . 'orders/' . $getOrderFolderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $getOrderFolderId . '.png?rvn='. $rvnUniqeNo;
								$svgUrl = ASSETS_PATH_R . 'orders/' . $getOrderFolderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $getOrderFolderId . '.svg?rvn='. $rvnUniqeNo;
								if (!file_exists($pngPath)) {
									$orderDwonloadObj->svgConvertToPng($pngPath, $svgPath);
								}
								if ($profile['isDesigned'] > 0) {
									$decorationData[] = [
										'decoration_name' => isset($profile['name']) ? $profile['name'] : "",
										'print_area_id' => $profile['print_area']['id'],
										'print_area_name' => $profile['print_area']['name'],
										'print_profile_id' => $profile['print_method_id'],
										'print_profile_name' => $profile['print_method_name'],
										'print_unit' => $sideDetails['print_unit'],
										'print_area_height' => $profile['print_area']['height'],
										'print_area_width' => $profile['print_area']['width'],
										'design_width' => isset($profile['design_width']) ? $profile['design_width'] : "",
										'design_height' => isset($profile['design_height']) ? $profile['design_height'] : "",
										'svg_url' => $svgUrl,
										'png_url' => $pngUrl,
										'used_colors' => $profile['used_colors'] ? $profile['used_colors'] : [],
										'x_location' => isset($profile['design_x']) ? $profile['design_x'] : "",
										'y_location' => isset($profile['design_y']) ? $profile['design_y'] : "",
										'artwork_coordinates' => isset($profile['artwork_coordinates']) ? $profile['artwork_coordinates'] : [],
									];
								}
								$j++;
							}
						}
						$productDecoData[] = [
							'is_design' => $isDesign,
							'name' => $sideName,
							'decoration_data' => $decorationData,
							'configurator' => $configurator,
							'stickerInfo' => $stickerInfo,
							'sheet_key' => $itemKey,
						];
						$i++;
					}
				}
			} elseif ($orderDetails['custom_design_id'] < 0) {
				$orderFolderDir = path('abs', 'order') . $getOrderFolderId . '/order.json';
				if ($isS3Enabled || !file_exists($orderFolderDir)) {
					$orderIdPath = path('abs', 'order'). $getOrderFolderId;
					$this->downloadS3Content("/assets/orders/" . $getOrderFolderId, $orderIdPath, $storeId);
		            $jsonContent = json_decode(file_get_contents($orderIdPath . '/order.json'), true);
		        } else {
					$orderJson = read_file($orderFolderDir);
					$jsonContent = json_clean_decode($orderJson, true);
				}

				$orderItemArr = $jsonContent['order_details']['order_items'];
				$itemId = $orderDetails['id'];
				$itemArr = array_filter($orderItemArr, function ($item) use ($itemId) {
					return ($item['item_id'] == $itemId);
				});
				$itemArr = $itemArr[array_keys($itemArr)[0]];
				$filesDataArr = $itemArr['file_data'];
				if (!empty($filesDataArr)) {
					foreach ($filesDataArr as $files) {
						$decorationData = [];
						foreach ($files['decoration_area'] as $decorationArea) {
							$designImages[] = [
								'src' => $decorationArea['upload_preview_url'],
								'thumbnail' => $decorationArea['upload_preview_url'],
							];
							$decorationData[] = [
								'decoration_name' => $decorationArea['decoration_area'],
								'print_area_id' => $decorationArea['print_area_id'],
								'print_area_name' => $decorationArea['print_area_name'],
								'print_profile_id' => $decorationArea['print_method_id'],
								'print_profile_name' => $decorationArea['print_methods'],
								'print_unit' => $decorationArea['measurement_unit'],
								'print_area_height' => $decorationArea['height'],
								'print_area_width' => $decorationArea['width'],
								'design_width' => $decorationArea['design_width'],
								'design_height' => $decorationArea['design_height'],
								//'svg_url' => $decorationArea['upload_design_url'],
								'png_url' => $decorationArea['upload_design_url'],
							];
						}
						$productDecoData[] = [
							'is_design' => 1,
							'name' => $files['side_name'],
							'decoration_data' => $decorationData,
						];
					}
				}

			}

			$orderResponse[$orderDetailsKey] += [
				'decoration_settings_data' => $productDecoData,
			];

			if (!empty($designImages) && strtolower(STORE_NAME) != "shopify") {
				$orderResponse[$orderDetailsKey]['images'] = $designImages;
			}
			if (empty($designId) || !in_array($orderDetails['custom_design_id'], $designId)) {
				$notes[] = $jsonContent['notes'];
				$designId[] = $orderDetails['custom_design_id'];
			}
			if (strtolower(STORE_NAME) == "shopify") {
				$ordersStatus = $ordersInit->where('order_id', $orderDetails['order_id'])->first();
				$orderResponse[$orderDetailsKey]['status'] = (!empty($ordersStatus->order_status)) ? $ordersStatus->order_status : 'received';
			}
			$orderResponse[$orderDetailsKey]['store_image'] = $orderDetails['images'];
		}
		return $orderResponse;
	}

	/**
	 * Get list of product product As xml format for shipstation
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author steve@imprintnext.com
	 * @date   22 mar 2022
	 * @return Order List in Json format
	 */
	public function getOrdersForShipstation($request, $response, $args){

		$storeResponse = $this->getStoreOrders($request, $response, $args);
		//print_r($storeResponse); exit;
		$orderDetails =  $storeResponse['order_details'];
		$xml = '<?xml version="1.0" encoding="utf-8"?>';
		$perPage = 40;
		if($storeResponse['total_records'] >= $perPage){
			$pages = round($storeResponse['total_records'] / $perPage);
		} else{
			$pages = 1;
		}
		$xml .= '<Orders pages="'.$pages.'">';
		$xmlOrders ='';
		$items ='';
		foreach ($orderDetails as $value) {
			$args['id'] = $value['id']; 
			$orderDetails = $this->getStoreOrders($request, $response, $args);		
			

			$AwaitingPaymentStatusArray = array('awaiting bank wire payment','awaiting cash on delivery validation','awaiting check payment','payment accepted','processing in progress','remote payment accepted','pending','processing','incomplete','awaiting payment','manual verification required','processed','received','reopened','received','payment_review','paypal_canceled_reversal','paypal_reversed','pending_payment','pending_paypal');

			$AwaitingShipmentStatusesArray = array('Awaiting Pickup','Awaiting Shipment','awaiting fulfillment');

			$ShippedStatusArray = array('shipped','partially shipped','completed');

			$CancelledStatusArray = array('canceled','declined','disputed','denied','canceled reversal','failed','refunded','reversed','chargeback','voided','expired','closed');

			$OnHoldStatusArray = array('on-hold','holded','fraud');

			$orderDetails = $orderDetails['order_details'] ;
			$orderStatus = strtolower($orderDetails['status']);

			// Set Order Status
			if (in_array($orderStatus, $AwaitingPaymentStatusArray)){
				$orderStatus = 'payment processing';
			}elseif (in_array($orderStatus, $AwaitingShipmentStatusesArray)){
				$orderStatus = 'shipment processing';
			}elseif (in_array($orderStatus, $ShippedStatusArray)){
				$orderStatus = 'shipped';
			}elseif (in_array($orderStatus, $CancelledStatusArray)){
				$orderStatus = 'cancelled';
			}elseif (in_array($orderStatus, $OnHoldStatusArray)){
				$orderStatus = 'on_hold';
			}else{
				$orderStatus = '';
			}


			
			$xmlOrders .= '<Order>
			<OrderID><![CDATA['.$orderDetails['id'].']]></OrderID>
		    <OrderNumber><![CDATA['.$orderDetails['order_number'].']]></OrderNumber>
		    <OrderDate>'.date('m/d/Y h:m A', strtotime($orderDetails['created_date'])).'</OrderDate>
		    <OrderStatus><![CDATA['.strtolower($orderStatus).']]></OrderStatus>
		    <LastModified>'.date('m/d/Y h:m A', strtotime($orderDetails['updated_date']?$orderDetails['updated_date']:$orderDetails['created_date'])).'</LastModified>
		    <ShippingMethod><![CDATA[]]></ShippingMethod>
		    <PaymentMethod><![CDATA['.$orderDetails['payment'].']]></PaymentMethod>
		    <CurrencyCode>'.$orderDetails['currency'].'</CurrencyCode> 
		    <OrderTotal>'.$orderDetails['total_amount'].'</OrderTotal>
		    <TaxAmount>'.$orderDetails['total_tax'].'</TaxAmount>
		    <ShippingAmount>'.$orderDetails['total_shipping'].'</ShippingAmount>
		    <CustomerNotes><![CDATA['.$orderDetails['note'].']]></CustomerNotes>
		    <InternalNotes><![CDATA['.$orderDetails['note'].']]></InternalNotes>
		    <Gift>false</Gift>
		    <GiftMessage></GiftMessage>
		    <CustomField1></CustomField1>
		    <CustomField2></CustomField2>
		    <CustomField3></CustomField3>
		    <Customer>
		      <CustomerCode><![CDATA['.$orderDetails['billing']['email'].']]></CustomerCode>
		      <BillTo>
		        <Name><![CDATA['.$orderDetails['billing']['first_name'].''.$value['billing']['last_name'].']]></Name>
		        <Company><![CDATA['.$orderDetails['billing']['company'].']]></Company>
		        <Phone><![CDATA['.$orderDetails['billing']['phone'].']]></Phone>
		        <Email><![CDATA['.$orderDetails['billing']['email'].']]></Email>
		      </BillTo>
		      <ShipTo>
		        <Name><![CDATA['.$orderDetails['shipping']['first_name'].''.$value['shipping']['last_name'].']]></Name>
		        <Company><![CDATA['.$orderDetails['shipping']['company'].']]></Company>
		        <Address1><![CDATA['.$orderDetails['shipping']['address_1'].']]></Address1>
		        <Address2>'.$orderDetails['shipping']['address_2'].'</Address2>
		        <City><![CDATA['.$orderDetails['shipping']['city'].']]></City>
		        <State><![CDATA['.$orderDetails['shipping']['state'].']]></State>
		        <PostalCode><![CDATA['.$orderDetails['shipping']['postcode'].']]></PostalCode>
		        <Country><![CDATA['.trim($orderDetails['shipping']['country_code']).']]></Country>
		        <Phone><![CDATA['.$orderDetails['shipping']['phone'].']]></Phone>
		      </ShipTo>
		    </Customer>';
		    $items = '<Items>';
		    $designedImageArr = $this->getOrderDesignedImage($orderDetails['orders'], $request);
		    foreach ($orderDetails['orders'] as $orderKey => $orderValue) {
		    	$designedImage = $designedImageArr[$orderKey]['images'][0]['src'];
		    	$xmlImage = $designedImage != '' ? $designedImage : $orderValue['images'][0]['src'] ;
				if($orderDetails['weight_unit'] == 'kg'){
					$orderWeight = $orderValue['weight'] * 1000;
					$weight_unit = 'Grams';
				}
				$items .= '<Item>
				<SKU><![CDATA['.$orderValue['sku'].']]></SKU>
		        <Name><![CDATA['.$orderValue['name'].']]></Name>
		        <ImageUrl><![CDATA['.$xmlImage.']]></ImageUrl>
		        <Weight>'.$orderWeight.'.00</Weight>
		        <WeightUnits>'.$weight_unit.'</WeightUnits>
		        <Quantity>'.$orderValue['quantity'].'</Quantity>
		        <UnitPrice>'.$orderValue['price'].'</UnitPrice>
		        <Location><![CDATA[]]></Location>';
		        if($orderValue['type'] =='variable'){
		        	$items .= '<Options>';
		        	foreach ($orderValue['options'] as $optionsValue) {	  		
		        		$items .= '<Option>
				          <Name><![CDATA['.str_replace("attribute_pa_","",$optionsValue['optionsKey']).']]></Name>
				          <Value><![CDATA['.$optionsValue.']]></Value>
				         <!-- - <Weight>0.00</Weight> <!- -->
				        </Option>';
				    }
				    $items .= '</Options>';
	       			$items .= '<Adjustment>0</Adjustment>';
	       		}
		        else{
		        	$items .= '<Adjustment>0</Adjustment>';
		        }
		        $items .= '</Item>';
		    }
		    $items .= '</Items>';
		    $xmlOrders .= $items;
		    $items = '';
		    $xmlOrders .= '</Order>';
		}
		$xml .= $xmlOrders;
		//$xmlOrders = '';
		$xml .= '</Orders>';
		return $xml;
	}


	/**
	 * Get list of product product As xml format for shipstation
	 *
	 * @param $orders  Slim's Request object
	
	 *
	 * @author steve@imprintnext.com
	 * @date   22 mar 2022
	 * @return Order designed Image
	 */
	public function getOrderDesignedImage($orders, $request){
		foreach ($orders as $orderDetailsKey => $orderDetails) {
			$designImages = [];
			$productDecoData = [];
			$args = [];
			if ($orderDetails['custom_design_id'] > 0) {
				$isPurchaseorder = $request->getQueryParam('isPurchaseorder') ? $request->getQueryParam('isPurchaseorder') : false;	
				$orderFolderDir = path('abs', 'order') . $args['id'] . '/order.json';
				$jsonFile = read_file($orderFolderDir);
				$jsonFileContent = json_clean_decode($jsonFile, true);
				$quoteSource =  isset($jsonFileContent['order_details']['quote_source']) ? $jsonFileContent['order_details']['quote_source'] : '';
				$customDesignId = $orderDetails['custom_design_id'];
				$deisgnStatePath = path('abs', 'design_state') . 'carts';
				$predecoPath = path('abs', 'design_state') . 'predecorators';
				$quotationPath = path('abs', 'design_state') . 'artworks';
				$orderJsonPath = $deisgnStatePath . '/' . $customDesignId . ".json";
				$orderPredecoPath = $predecoPath . '/' . $customDesignId . ".json";
				$orderQuotationPath = $quotationPath . '/' . $customDesignId . ".json";
				if (file_exists($orderJsonPath)) {
					$orderJson = read_file($orderJsonPath);
					$jsonContent = json_clean_decode($orderJson, true);
				} elseif (file_exists($orderPredecoPath)) {
					$orderJson = read_file($orderPredecoPath);
					$jsonContent = json_clean_decode($orderJson, true);
				} elseif (file_exists($orderQuotationPath)) {
					$orderJson = read_file($orderQuotationPath);
					$jsonContent = json_clean_decode($orderJson, true);
				}else{
					$orderJson = "";
					$jsonContent = "";

				}

				// code for svg configurator data fetcehd from desoginstate.json//
                

				if (!$isPurchaseorder && !empty($jsonContent['design_product_data'])) {
						$variantIdArr = [];
						foreach ($jsonContent['design_product_data'] as $designImage) {
							// Added for same product image for artwork
							if ((file_exists($orderQuotationPath) && ($quoteSource == '' && $quoteSource == 'admin')) || file_exists($orderPredecoPath)) {
								$designImages = [];
								if (!empty($designImage['design_urls'])) {
									foreach ($designImage['design_urls'] as $image) {
										$designImages[] = [
											'src' => $image,
											'thumbnail' => $image,
										];
									}
								}
							} else {
								if (($orderDetails['variant_id'] == 0 || in_array($orderDetails['variant_id'], $designImage['variant_id'])) && !in_array($orderDetails['variant_id'], $variantIdArr)) {
										array_push($variantIdArr, $orderDetails['variant_id']);
										if (!empty($designImage['design_urls'])) {
											foreach ($designImage['design_urls'] as $image) {
												$designImages[] = [
													'src' => $image,
													'thumbnail' => $image,
												];
											}
										}
								}
							}							
						}
				}

				
			} else {
				$orderFolderDir = path('abs', 'order') . $args['id'] . '/order.json';
				$orderJson = read_file($orderFolderDir);
				$jsonContent = json_clean_decode($orderJson, true);
				//echo'<pre>';print_r($jsonContent);exit;
				$orderItemArr = $jsonContent['order_details']['order_items'];
				$itemId = $orderDetails['id'];
				$itemArr = array_filter($orderItemArr, function ($item) use ($itemId) {
					return ($item['item_id'] == $itemId);
				});
				$itemArr = $itemArr[array_keys($itemArr)[0]];
				$filesDataArr = $itemArr['file_data'];
				if (!empty($filesDataArr)) {
					foreach ($filesDataArr as $files) {
						$decorationData = [];
						foreach ($files['decoration_area'] as $decorationArea) {
							$designImages[] = [
								'src' => $decorationArea['upload_preview_url'],
								'thumbnail' => $decorationArea['upload_preview_url'],
							];
							$decorationData[] = [
								'decoration_name' => $decorationArea['decoration_area'],
								'print_area_id' => $decorationArea['print_area_id'],
								'print_area_name' => $decorationArea['print_area_name'],
								'print_profile_id' => $decorationArea['print_method_id'],
								'print_profile_name' => $decorationArea['print_methods'],
								'print_unit' => $decorationArea['measurement_unit'],
								'print_area_height' => $decorationArea['height'],
								'print_area_width' => $decorationArea['width'],
								'design_width' => $decorationArea['design_width'],
								'design_height' => $decorationArea['design_height'],
								//'svg_url' => $decorationArea['upload_design_url'],
								'svg_artwork_url' => $decorationArea['upload_design_url'],
								'png_url' => $decorationArea['upload_design_url'],
							];
						}
						$productDecoData[] = [
							'is_design' => 1,
							'name' => $files['side_name'],
							'decoration_data' => $decorationData,
						];
					}
				}

			}				
			//Get product description
			
			if (!empty($designImages)) {
				$storeResponse['order_details']['orders'][$orderDetailsKey]['images'] = $designImages;
			}
			if (empty($designId) || !in_array($customDesignId, $designId)) {
				if ($jsonContent['notes'] != '') {
					$notes[] = $jsonContent['notes'];
				}
				$designId[] = $customDesignId;
			}
			if (strtolower(STORE_NAME) == "shopify") {
				$ordersInit = new Orders();
				$ordersStatus = $ordersInit->where('order_id', $storeResponse['order_details']['id'])->first();
				$storeResponse['order_details']['status'] = (!empty($ordersStatus->order_status)) ? $ordersStatus->order_status : 'received';
			}
		}
		return $storeResponse['order_details']['orders'];
	}
	/**
	 *
	 * Create order bar code
	 * @param $orderId
	 * @author soumyas@riaxe.com
	 * @date   20 April 2022
	 * @return int
	 *
	 */
	public function createOrderBarCode($orderId) {
		$barCodeStatus = 0;
		$orderId = "order-".$orderId;
		$barCodePath =  ASSETS_PATH_W.'bar_codes/'.$orderId.'.png';
		$barcode = generate_barcode($orderId);
		$filePutStatus =  file_put_contents($barCodePath, $barcode);
		if($filePutStatus) {
			$barCodeStatus=1;
		}
		return $barCodeStatus;
	}

	/**
	 * GET: Generate Order Invoice PDF
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Args object
	 *
	 * @author diana@imprintnext.com
	 * @date   23 Feb 2022
	 * @return json
	 */
	public function downloadOrderInvoice($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Packing Slip Download', 'error'),
		];
		$orderIncrementId = $request->getQueryParam('order_increment_id') ? $request->getQueryParam('order_increment_id') : 0;
		//$showPrice = $request->getQueryParam('show_price') ? $request->getQueryParam('show_price') : 0;
		$orderAssetPath = path('abs', 'order') . $orderIncrementId;
		if (is_dir($orderAssetPath)) {
			$orderId = $orderIncrementId;
		} else {
			$orderId = $args['id'];
		}
		$getStoreDetails = get_store_details($request);
		$storeId = $getStoreDetails['store_id'] ? $getStoreDetails['store_id'] : 1;
		//Get order seeting from general settings
		$settingInit = new \App\Modules\Settings\Models\Setting();
		$getSettings = $settingInit->where('type', '>', 0);
		$orderSetting = [];
		$packageSlipNotes = $pakageSlipAddress = $packingSlipLogo = '';
		$pdfLanguage = $this->languageContent['order-pdf'];
		// Fetch language
		$languageInit = new Language();
        $where = ['type' => 'admin', 'is_default' => 1, 'store_id'=> $storeId];
        $getLanguage = $languageInit->where($where)->first()->toArray();
		// End
		$rtlLeftAlign = "right";
		$rtlRightAlign = "left";
		if ($getLanguage['name'] == 'Arabic') {
			$rtlLeftAlign = "left";
			$rtlRightAlign = "right";
		}
		$packageSlipStoreUrl = '';
		if ($getSettings->count() > 0) {
			$data = $getSettings->get();
			foreach ($data as $value) {
				if ($value['type'] == 6) {
					$packingSlipLogo = $this->getPackingSlipLogo($storeId);
					$orderSetting['packing_slip_logo'] = $packingSlipLogo;
					$orderSetting[$value['setting_key']] = json_clean_decode(
						$value['setting_value'], true
					) ? json_clean_decode(
						$value['setting_value'], true
					) : $value['setting_value'];
				}
			}
			if ($orderSetting['package_slip']['is_package_slip_notes']) {
				$packageSlipNotes = $orderSetting['package_slip']['package_slip_notes'] ? $orderSetting['package_slip']['package_slip_notes'] : '';
				$packageSlipNotes = str_replace('  ', ' &nbsp;', nl2br(htmlentities($packageSlipNotes)));
			}
			$pakageSlipAddress = $orderSetting['package_slip']['package_slip_address'] ? $orderSetting['package_slip']['package_slip_address'] : '';
			$pakageSlipAddress = str_replace('  ', ' &nbsp;', nl2br(htmlentities($pakageSlipAddress)));
			$orderSetting['package_slip']['is_package_slip_image_inlude'] ? true : false;
			$packageSlipStoreUrl = $orderSetting['package_slip']['package_slip_url'] ? $orderSetting['package_slip']['package_slip_url'] : '';
		}
		/** get font for default language */
		$languageFont =  $this->getDefaultLanguageFont($storeId, "admin");
		if ($getLanguage['name'] == "Japanese" || $getLanguage['name'] == "Chinese") {
			$fontFamily = "simsun";
			$fontAll = "simsun";
			$fontUrl = "";
		} else {
			$fontFamily = "DejaVuSans";
			$fontAll = "DejaVuSans";
			$fontUrl = "";
		}
		$fontStyle = $languageFont['font_style'];
		$fontWeight = $languageFont['font_weight'];
		$trueType = $languageFont['true_type'];
		if (!empty($args) && $orderId && !empty($orderSetting)) {
			$args['is_return'] = true;
			$order = $this->getOrderDetails($request, $response, $args);
			if (!empty($order) && $order['order_details']) {
				$barcode = generate_barcode($orderId);
				$barcodeImageSrc = 'data:image/png;base64,' . base64_encode($barcode);
				$orderDetails = $order['order_details'];
				$totalPrice = ($orderDetails['total_amount'] + $orderDetails['total_tax'] + $orderDetails['total_shipping']) - $orderDetails['total_discounts'];
				$createDate = $orderDetails['created_date'];
				$orderDate = date('jS F, Y', strtotime($createDate));
				$storeUrl = $packageSlipStoreUrl ? $packageSlipStoreUrl : $orderDetails['store_url'];
				$orderPath = path('abs', 'order');
				$orderIdPath = $orderPath . $orderId . '/';
				$html = '<html>
					<head>
						<title>'.$pdfLanguage['invoice'].'</title>
						<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
						<style>@media print {
					        body {-webkit-print-color-adjust: exact;}
					    }
					    @font-face {
	                      font-family: "'.$fontFamily.'";
	                      font-style: '.$fontStyle.';
	                      font-weight: '.$fontWeight.';
	                      src: url('.$fontUrl.') format("'.$trueType.'");
	                    }
	                    * {
							font-family: '.$fontAll.';
					    }
						</style>
					</head>
					<body>
						<table width="100%" cellpadding="0" cellspacing="0" border="0" style="font-family: '.$fontFamily.';">
					        <tr>
					            <td>
					                <table width="100%" cellpadding="0" cellspacing="0" border="0">
				                        <tr>
				                            <td width="50%">
				                            	<br/>
				                                <span><img src="' . $packingSlipLogo . '" width="100px"></span><br/>
				                                <span style="font-size:14px; margin: 10px 0 8px 0;">' . $pakageSlipAddress . '</span><br/>
				                                <span style="font-size:14px; margin: 0px 0 0px 0;">' . $storeUrl . '</span><br/>
				                            </td>';
				                            $html .= '<td width="50%" align="'.$rtlLeftAlign.'"><span style="font-size: 22px;font-weight:bold;">'.$pdfLanguage['invoice'].'</span><br/>
				                                <span style="font-size:14px; margin: 0 0 5px 0;"><b>'.$pdfLanguage['id'].' :</b> #' . $orderDetails['id'] . '</span><br/>
				                                <span style="font-size:14px; margin: 0 0 5px 0;"><b>'.$pdfLanguage['date'].' :</b> ' . $orderDate . '</span><br/>
				                                <span style="font-size:14px; margin: 0 0 0px 0;"><b>'.$pdfLanguage['payment-mode'].' :</b> ' . $orderDetails['payment'] . '</span><br/><br/>
				                               <span style="font-size: 28px;"><img src="@' . preg_replace('#^data:image/[^;]+;base64,#', '', $barcodeImageSrc) . '" style="height:100%; max-height:30px;"></span>
				                            </td>
				                        </tr>
					                </table>
					            </td>
					        </tr>
					        <tr>
					            <td>
					                <hr style="margin: 30px 0 0 0;">
					            </td>
					        </tr>
					        <tr>
					            <td>
					                <table width="100%">
				                        <tr>';
					                        $html .= '<td width="50%" align="'.$rtlRightAlign.'">
				                            	<br/>
				                                <span style="padding: 0; margin: 0 0 5px 0; font-size: 18px;font-weight:bold;">'.$pdfLanguage['bill-to'].'</span><br/>
				                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['billing']['first_name'] . ' ' . $orderDetails['billing']['last_name'] . '</span><br/>
				                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['billing']['address_1'] . ' ' . $orderDetails['billing']['address_2'] . '</span><br/>
				                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['billing']['city'] . ', ' . $orderDetails['billing']['state'] . ', ' . $orderDetails['billing']['postcode'] . ',' . $orderDetails['billing']['phone'] . '</span><br/>
				                            </td>';
					                        $html .= '<td width="50%" align="'.$rtlLeftAlign.'">
				                            	<br/>
				                                <span style="padding: 0; margin: 0 0 10px 0; font-size: 18px;font-weight:bold;">'.$pdfLanguage['ship-to'].'</span><br/>
				                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['shipping']['first_name'] . ' ' . $orderDetails['shipping']['last_name'] . '</span><br/>
				                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['shipping']['address_1'] . ' ' . $orderDetails['shipping']['address_2'] . '</span><br/>
				                                <span style="padding: 0; margin: 0 0 5px 0; font-size:14px;">' . $orderDetails['shipping']['city'] . ', ' . $orderDetails['shipping']['state'] . ', ' . $orderDetails['shipping']['postcode'] . ',' . $orderDetails['shipping']['phone'] . '</span><br/>
				                            </td>
				                        </tr>
					                </table>
					            </td>
					        </tr>
					        <tr>
					        	<td>
						            <table width="100%" cellpadding="5" cellspacing="0" border="0" style="font-size:13px; margin: 30px 0 0 0; font-family: '.$fontFamily.';">
						                    <tr>
						                      <td align="'.$rtlRightAlign.'" bgcolor="#e3e4e6" width="6%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">'.$pdfLanguage['no'].'</td>
						                      <td align="'.$rtlRightAlign.'" bgcolor="#e3e4e6" width="54%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">'.$pdfLanguage['product'].'</td>
						                      <td align="'.$rtlRightAlign.'" bgcolor="#e3e4e6" width="20%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">'.$pdfLanguage['quantity'].'</td>';
				                            $html .= '
							                      <td align="'.$rtlLeftAlign.'" bgcolor="#e3e4e6" width="20%" style="padding: 10px; border: 1px solid #aaa;font-weight:bold;">'.$pdfLanguage['price'].'</td>
							                    </tr>';
						                    foreach ($orderDetails['orders'] as $k => $item) {
							                	$no = $k + 1;
							                	$html .= '<tr>
							                        <td align="'.$rtlRightAlign.'" style="padding: 10px; border: 1px solid #aaa;">
							                            '.$no.'
							                        </td>
							                        <td align="'.$rtlRightAlign.'" style="padding: 10px; border: 1px solid #aaa;">' . $item['name'] . '
							                        </td>
							                        <td align="'.$rtlRightAlign.'" style="padding: 10px; border: 1px solid #aaa;">
							                            ' . $item['quantity'] . '
							                        </td>
							                        <td style="text-align: '.$rtlLeftAlign.'; padding: 10px; border: 1px solid #aaa;">
							                            ' . number_format($item['price'], 2) . ' ' . $orderDetails['currency'] . '
							                        </td>
							                    </tr>';
							                }

						                	$html .= '<tr>
						                        <td colspan="2">
						                        </td>
						                        <td style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;border-left: 1px solid #aaa;font-weight:bold;">
						                            '.$pdfLanguage['subtotal'].'
						                        </td>
						                        <td style="text-align: '.$rtlLeftAlign.'; padding: 10px; border: 1px solid #aaa;">
						                            ' . number_format($orderDetails['total_amount'], 2) . ' ' . $orderDetails['currency'] . '
						                        </td>
						                    </tr>
						                    <tr>
						                        <td colspan="2">
						                        </td>
						                        <td style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;border-left: 1px solid #aaa;font-weight:bold;">
						                            '.$pdfLanguage['tax'].'
						                        </td>
						                        <td style="text-align: '.$rtlLeftAlign.'; padding: 10px; border: 1px solid #aaa;">
						                            ' . number_format($orderDetails['total_tax'], 2) . ' ' . $orderDetails['currency'] . '
						                        </td>
						                    </tr>
						                    <tr>
						                        <td colspan="2">
						                        </td>
						                        <td style="text-align: '.$rtlRightAlign.'; padding: 10px; border: 1px solid #aaa;border-left: 1px solid #aaa;font-weight:bold;">
						                            '.$pdfLanguage['total'].'
						                        </td>
						                        <td style="text-align: '.$rtlLeftAlign.'; padding: 10px; border: 1px solid #aaa;">
						                            ' . number_format($totalPrice, 2) . ' ' . $orderDetails['currency'] . '
						                        </td>
						                    </tr>
						            </table>
					            </td>
					        </tr>
						</table>
					</body>
				</html>';
				$fileName = create_tcpdf($html, $orderIdPath, 'Invoice-'.$orderDetails['id'], $lang=$getLanguage['name']);
				$dir = $orderIdPath . $fileName;
				//Download file in local system
				if (file_download($dir)) {
					$serverStatusCode = OPERATION_OKAY;
					$jsonResponse = [
						'status' => 1,
					];
				}
			}
		}
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * Internal: Update catalog order status
	 *
	 * @param $orderId  Order Id
	 * @param $updateData Order Status
	 *
	 * @author steve@imprintnext.com
	 * @date   5 Sept 2021
	 * @return boolean
	 */

	private function updateCatalogOrderStatus($orderId, $updateData, $storeId){
		if( $updateData['statusKey'] == '10' || $updateData['statusKey'] == 'completed' || $updateData['statusKey'] == 'received' || $updateData['statusKey'] == 'Delivered' || $updateData['statusKey'] == 'complete' ) {
			$IntegrationObj = new IntegrationController();
	        $printfulPluginId = $IntegrationObj->getPluginId('printful');
			$CatalogOrderRelObj = new CatalogOrderRel();
			$totalCatOrders = $CatalogOrderRelObj->select('*')
			->where(['catalog_code' => $printfulPluginId])
			->where(['order_id' => $orderId]);
			if($totalCatOrders->count() >= 1){
				$orderStatusData['report'] = 'archive'; 
				$CatalogOrderRelObj->where(["order_id"=> $orderId])->update($orderStatusData);
				return 1;
			}
		}
		return 0;
	}
	/*
	 * GET : Order details by order ids
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@riaxe.com
	 * @date   08 Nov 2022
	 * @return json
	 */
	public function getOrderShortDetailsById($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 1,
			'data' => [],
			'message' => message('Order details', 'error'),
		];
		if( $args['is_purchase_order'] == 1 && !empty($args['orders_ids']) ) {
			return $this->getOrderShortDetails($args['orders_ids'], $args['store_id']);
		}
		$jsonResponse = [
			'status' => 1,
			'data' => []
		];
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}

	/**
	 * Internal: Update catalog order status
	 *
	 * @param $request  Slim Request
	 * @param $response  Slim response
	 * @param $args 
	 * @param $returnType 
	 *
	 * @author steve@imprintnext.com
	 * @date   22 Nov 2022
	 * @return boolean
	 */

	private function listPrintfulOrder($request, $response, $args){
		$orderby = $request->getQueryParam('orderby') ? $request->getQueryParam('orderby') : 'desc';
		$page = $request->getQueryParam('page') ? $request->getQueryParam('page') : 1;
		$perPage = 10;
		
		if($page == 1) {
			$startLimit = 0;
		}
		else{
			$startLimit = ($page-1) * $perPage;
		}
		
		$catalogCode = $request->getQueryParam('catalog_code') ? $request->getQueryParam('catalog_code') : '';
		$orderby = $request->getQueryParam('orderby') ? $request->getQueryParam('orderby') : 'desc';
		$page = $request->getQueryParam('page') ? $request->getQueryParam('page') : 1;
		$perPage = 10;
	
		$IntegrationObj = new IntegrationController();
		$printfulPluginId = $IntegrationObj->getPluginId($catalogCode);
		$CatalogOrderRelObj = new CatalogOrderRel();
	
		$totalCatOrders = $CatalogOrderRelObj->select('*')
		->where(['catalog_code' => $printfulPluginId])
		->where('report' , '<>', 'archive');
		$totalCatOrders = $totalCatOrders->count();
	
		$catlogOrderData = $CatalogOrderRelObj->select('*')
		->where(['catalog_code' => $printfulPluginId])
		->where('report' , '<>', 'archive')
		->orderBy('order_id',$orderby)->offset($startLimit)->limit($perPage)
		->get()->toArray();
	
		$storeResponse['total_records'] = $totalCatOrders;
		$storeResponse['order_details'] = [] ;
		
		foreach ($catlogOrderData as $value) {
			$args['id'] = $value['order_id'];
			$printfulOrderDetail = $this->getStoreOrders($request, $response, $args);
			$OrderDetail = $printfulOrderDetail['order_details'];
			$storeResponse['order_details'][] =[
				"id" => $OrderDetail['id'],
				"order_number" => $OrderDetail['order_number'],
				"order_total_quantity"=> $printfulOrderDetail['total_records'],
				"customer_first_name" => $OrderDetail['customer_first_name'],
				"customer_last_name" => $OrderDetail['customer_last_name'],
				"created_date" => $OrderDetail['created_date'],
				"total_amount" => $OrderDetail['total_amount'],
				"currency" => $OrderDetail['currency'],
				"is_customize" => 1,
				"production" => "",
				"status" =>  $OrderDetail['status'],
				"catalog_code" => 'printful',
				"catalog_order_id" => $value['catalog_order_id'],
				"report" => $value['report'],
				"catlog_order_status" => $value['status'],
			];        
		}
		return $storeResponse;
	}
	
	/**
	 * Internal: Update catalog order status
	 *
	 * @param $printfulPluginId  Slim Request
	 * @param $orderId  Slim response
	 *
	 * @author steve@imprintnext.com
	 * @date   22 Nov 2022
	 * @return boolean
	 */
	private function getPrintfulOrderStatus($printfulPluginId,$orderId){
		$CatalogOrderRelObj = new CatalogOrderRel();
		
		$totalCatOrders = $CatalogOrderRelObj->select('*')
		->where(['catalog_code' => $printfulPluginId])
		->where(['order_id' => $orderId]);
		
		if($totalCatOrders->count()){
			$totalCatOrders = $totalCatOrders->first()->toArray();
			$shipping = json_clean_decode($totalCatOrders['shipping']);
			$storeResponse['tracking_url'] = $shipping['tracking_url'];
			$storeResponse['carrier'] = $shipping['carrier'];
			$storeResponse['ship_date'] = $shipping['ship_date'];
			$storeResponse['catalog_order_id'] = $totalCatOrders['catalog_order_id'];
			$printfullObj = new PrintfulController();
			$catalogOrderDetails = $printfullObj->printfulGetOrderDetail($totalCatOrders['catalog_order_id']);
			$catalogOrderStatus = $catalogOrderDetails['status'];
			$storeResponse['catalog_order_status'] = $catalogOrderStatus;
			return($storeResponse);
		}
	}
	
	/**
	 * Internal: Update catalog order status
	 *
	 * @param $shipstationPluginId
	 * @param $orderId
	 *
	 * @author steve@imprintnext.com
	 * @date   22 Nov 2022
	 * @return boolean
	 */
	private function shipStationOrder($shipstationPluginId, $orderId){
		$CatalogOrderRelObj = new CatalogOrderRel();
		
		$totalCatOrders = $CatalogOrderRelObj->select('*')
		->where(['catalog_code' => $shipstationPluginId ])
		->where(['order_id' => $orderId]);
		
		if($totalCatOrders->count()){
			$totalCatOrders = $totalCatOrders->first()->toArray();
			$shipping = json_clean_decode($totalCatOrders['shipping']);
	
			$storeResponse['order_details']['ship_station']['tracking_number'] = $shipping['TrackingNumber'];
			$storeResponse['order_details']['ship_station']['carrier'] = $shipping['Carrier'];
			$storeResponse['order_details']['ship_station']['ship_date'] = date('Y-m-d',strtotime($shipping['ShipDate']));
			
		}
	}

	/**
	 * Internal: Update catalog order status
	 *
	 * @param $storeResponse  
	 *
	 * @author steve@imprintnext.com
	 * @date   22 Nov 2022
	 * @return boolean
	 */
	private function generateDecoratedData($request,$storeResponse, $thisOrderId, $args){
		$isPurchaseorder = $request->getQueryParam('isPurchaseorder') ? $request->getQueryParam('isPurchaseorder') : false;	
		$jsonContent = "";
		$designId = [];
		$notes = [];
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
		foreach ($storeResponse['order_details']['orders'] as $orderDetailsKey => $orderDetails) {
			if (strtolower(STORE_NAME) == "others") {
				if($orderDetails['line_items']){
					$orderDetails = $orderDetails['line_items'][0];
				}
	    	}
			if(!in_array('overlogo', $args['list_exclude']) && array_key_exists('overlogo_id', $orderDetails) && $orderDetails['overlogo_id'] != "") {
				// If overlogo product replace store image to overlogo preview image
				$overLogoID = $orderDetails['overlogo_id'];
				$overlogoPreviewImg = ASSETS_PATH_R . "overlogo/cartproductimage/" . $overLogoID . "/preview.jpg";
				$storeResponse['order_details']['orders'][$orderDetailsKey]['images'][0]['src'] = $overlogoPreviewImg;
				$storeResponse['order_details']['orders'][$orderDetailsKey]['images'][0]['thumbnail'] = $overlogoPreviewImg;
				//Get logo file
				$all_files = glob(ASSETS_PATH_W . "overlogo/cartproductimage/" . $overLogoID . "/*.*");
				foreach ($all_files as $filename) {
					$name = basename($filename);
					$fileNameOnly = pathinfo($filename, PATHINFO_FILENAME);
					if ($fileNameOnly != "preview") {
						$storeResponse['order_details']['orders'][$orderDetailsKey]['logo_data'][0]['logo_url'] = ASSETS_PATH_R . "overlogo/cartproductimage/" . $overLogoID . "/" . $name;
					}
				}
			}
			$designImages = [];
			$productDecoData = [];
			
			if ($orderDetails['custom_design_id'] > 0) {
				$orderFolderDir = path('abs', 'order') . $args['id'] . '/order.json';
				$customDesignId = $orderDetails['custom_design_id'];
				$deisgnStatePath = path('abs', 'design_state') . 'carts';
				$predecoPath = path('abs', 'design_state') . 'predecorators';
				$quotationPath = path('abs', 'design_state') . 'artworks';
				$orderJsonPath = $deisgnStatePath . '/' . $customDesignId . ".json";
				$orderPredecoPath = $predecoPath . '/' . $customDesignId . ".json";
				$orderQuotationPath = $quotationPath . '/' . $customDesignId . ".json";
				
				if (file_exists($orderJsonPath)) {
					$orderJson = read_file($orderJsonPath);
					$jsonContent = json_clean_decode($orderJson, true);
				} elseif (file_exists($orderPredecoPath)) {
					$orderJson = read_file($orderPredecoPath);
					$jsonContent = json_clean_decode($orderJson, true);
				} elseif (file_exists($orderQuotationPath)) {
					$orderJson = read_file($orderQuotationPath);
					$jsonContent = json_clean_decode($orderJson, true);
				}
				$storeResponse['order_details']['orders'][$orderDetailsKey]['design_price'] = isset($jsonContent['added_price']) ? $jsonContent['added_price'] : 0;
				// code for svg configurator data fetcehd from desoginstate.json//
				$svgConfiguratorArr = [];
				if (!empty($jsonContent['configurator_svg_info'])) {
					$svgConfiguratorArr = $jsonContent['configurator_svg_info'];
				}

				if (!$isPurchaseorder && !empty($jsonContent['design_product_data'])) {
						$variantIdArr = [];
						foreach ($jsonContent['design_product_data'] as $designImage) {
							// Added for same product image for artwork
							
							if (file_exists($orderQuotationPath) || file_exists($orderPredecoPath)) {
								$designImages = [];
								
								if (!empty($designImage['design_urls'])) {
									foreach ($designImage['design_urls'] as $image) {
										$designImages[] = [
											'src' => $image,
											'thumbnail' => $image,
										];
									}
								}
							} else {
							if (($orderDetails['variant_id'] == 0 || in_array($orderDetails['variant_id'], $designImage['variant_id'])) &&
								!in_array($orderDetails['variant_id'], $variantIdArr)
							) {

								array_push($variantIdArr, $orderDetails['variant_id']);
								
								if (!empty($designImage['design_urls'])) {
									foreach ($designImage['design_urls'] as $image) {
										$designImages[] = [
											'src' => $image,
											'thumbnail' => $image,
										];
									}
								}
							}
						}
							$storeResponse['order_details']['orders'][$orderDetailsKey]['variableDecorationSize'] = isset($designImage['variable_decoration_size']) ? $designImage['variable_decoration_size'] : '';
							$storeResponse['order_details']['orders'][$orderDetailsKey]['variableDecorationUnit'] = isset($designImage['variable_decoration_unit']) ? $designImage['variable_decoration_unit'] : '';
							$storeResponse['order_details']['orders'][$orderDetailsKey]['configurator_svg_info'] = $svgConfiguratorArr;
						}
					
				}

				if (!empty($jsonContent['sides'])) {
					$i = 1;
					foreach ($jsonContent['sides'] as $sideDetailsKey => $sideDetails) {
						$configurator = [];
						
						if (isset($sideDetails['configurator']) && !empty($sideDetails['configurator'])) {
							$configurator = $sideDetails['configurator'];
						}
						$sideName = !empty($sideDetails['side_name']) ? $sideDetails['side_name'] : "";
						$isDesign = !empty($sideDetails['is_designed']) ? $sideDetails['is_designed'] : 0;
						$decorationData = [];
						
						if (!empty($sideDetails['print_area'])) {
							$j = 0;
							foreach ($sideDetails['print_area'] as $profile) {
								$orderDwonloadObj = new OrderDownloadController();
								if (array_key_exists('is_single_printfile_enabled', $profile) && $profile['is_single_printfile_enabled']) {
									$svgUrl = ASSETS_PATH_R . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/single_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.svg';
									$svgPath = ASSETS_PATH_W . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/single_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.svg';
									$pngPath = ASSETS_PATH_W . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/single_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.png';
									$pngUrl = ASSETS_PATH_R . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/single_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.png';
									$pdfUrl = ASSETS_PATH_R . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/single_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.pdf';
								} else {
									$svgUrl = ASSETS_PATH_R . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.svg';
									$svgPath = ASSETS_PATH_W . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.svg';
									$pngPath = ASSETS_PATH_W . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.png';
									$pngUrl = ASSETS_PATH_R . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.png';
									$pdfUrl = ASSETS_PATH_R . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i . '/Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId . '.pdf';
								}
								if (!file_exists($pngPath)) {
									$orderDwonloadObj->svgConvertToPng($pngPath, $svgPath);
								}
								if ($profile['isDesigned'] > 0) {
									$decorationData[] = [
										'decoration_name' => isset($profile['name']) ? $profile['name'] : $profile['name'],
										'print_area_id' => $profile['print_area']['id'],
										'print_area_name' => $profile['print_area']['name'],
										'print_profile_id' => $profile['print_method_id'],
										'print_profile_name' => $profile['print_method_name'],
										'print_unit' => $sideDetails['print_unit'],
										'print_area_height' => $profile['print_area']['height'],
										'print_area_width' => $profile['print_area']['width'],
										'design_width' => isset($profile['design_width']) ? $profile['design_width'] : "",
										'design_height' => isset($profile['design_height']) ? $profile['design_height'] : "",
										//'svg_url' => $svgUrl,
										'svg_artwork_url' => $svgUrl,
										'png_url' => $pngUrl,
										'pdf_url' => $pdfUrl,	
										'used_colors' => $profile['used_colors'] ? $profile['used_colors'] : [],
										'used_patterns' => $profile['used_patterns'] ? $profile['used_patterns'] : [],
										'x_location' => isset($profile['design_x']) ? $profile['design_x'] : "",
										'y_location' => isset($profile['design_y']) ? $profile['design_y'] : "",
										'rotate' => isset($jsonContent['layer_data'][$sideDetailsKey][$j]['rotate']) ? $jsonContent['layer_data'][$sideDetailsKey][$j]['rotate'] : false,
										'artwork_coordinates' => isset($profile['artwork_coordinates']) ? $profile['artwork_coordinates'] : [],
									];
								}
								$j++;
							}
						}
						$productDecoData[] = [
							'is_design' => $isDesign,
							'name' => $sideName,
							'decoration_data' => $decorationData,
							'configurator' => $configurator,
							'stickerInfo' => $sideDetails['stickerInfo'],
						];
						$i++;
					}
				}
			} elseif ($orderDetails['custom_design_id'] < 0) {
				$orderFolderDir = path('abs', 'order') . $thisOrderId . '/order.json';
				$orderJson = read_file($orderFolderDir);
				if(!empty($orderJson)){
					$jsonContent = json_clean_decode($orderJson, true);
					$orderItemArr = $jsonContent['order_details']['order_items'];
					$itemId = $orderDetails['id'];
					$itemArr = array_filter($orderItemArr, function ($item) use ($itemId) {
						return ($item['item_id'] == $itemId);
					});
					$itemArr = $itemArr[array_keys($itemArr)[0]];
					$filesDataArr = $itemArr['file_data'];
				}
				if (!empty($filesDataArr)) {
					foreach ($filesDataArr as $files) {
						$decorationData = [];
						foreach ($files['decoration_area'] as $decorationArea) {
							$designImages[] = [
								'src' => $decorationArea['upload_preview_url'],
								'thumbnail' => $decorationArea['upload_preview_url'],
							];
							$decorationData[] = [
								'decoration_name' => $decorationArea['decoration_area'],
								'print_area_id' => $decorationArea['print_area_id'],
								'print_area_name' => $decorationArea['print_area_name'],
								'print_profile_id' => $decorationArea['print_method_id'],
								'print_profile_name' => $decorationArea['print_methods'],
								'print_unit' => $decorationArea['measurement_unit'],
								'print_area_height' => $decorationArea['height'],
								'print_area_width' => $decorationArea['width'],
								'design_width' => $decorationArea['design_width'],
								'design_height' => $decorationArea['design_height'],
								//'svg_url' => $decorationArea['upload_design_url'],
								'svg_artwork_url' => $decorationArea['upload_design_url'],
								'png_url' => $decorationArea['upload_design_url'],
							];
						}
						$productDecoData[] = [
							'is_design' => 1,
							'name' => $files['side_name'],
							'decoration_data' => $decorationData,
						];
					}
				}

			}
			$storeResponse['order_details']['orders'][$orderDetailsKey] += [
				'decoration_settings_data' => $productDecoData,
			];
			
			if (!in_array('getProductDescription', $args['list_exclude'])) {
				//Get product description
				$productId = $storeResponse['order_details']['orders'][$orderDetailsKey]['product_id'];
				$productsControllerInit = new ProductsController();
				$storeResponse['order_details']['orders'][$orderDetailsKey] += [
					'product_description' => $productsControllerInit->getStore()->getProductDescription($productId),
				];
			}
			
			if (!empty($designImages) && strtolower(STORE_NAME) != "shopify") {
				$storeResponse['order_details']['orders'][$orderDetailsKey]['images'] = $designImages;
			}
			
			if (empty($designId) || !in_array($customDesignId, $designId)) {
				if (!empty($jsonContent)) {
					$notes[] = $jsonContent['notes'];
				}
				$designId[] = $customDesignId;
			}
			
			if (strtolower(STORE_NAME) == "shopify") {
				$ordersInit = new Orders();
				$ordersStatus = $ordersInit->where('order_id', $storeResponse['order_details']['id'])->first();
				$storeResponse['order_details']['status'] = (!empty($ordersStatus->order_status)) ? $ordersStatus->order_status : 'received';
			}
			
			if (!in_array('poStatus', $args['list_exclude'])) {
				$poStatus = $this->getOrderPoStatus($args['id'], $orderDetails['id'], $storeId);
				$storeResponse['order_details']['orders'][$orderDetailsKey]['po_status'] = $poStatus;
			}
			$storeResponse['order_details']['orders'][$orderDetailsKey]['store_image'] = $orderDetails['images'];
		}
		$storeResponse['notes'] = $notes;
		return $storeResponse;
	}
	/**
	 * Internal: Getting default Language Content
	 *
	 * @param $type  type of language
	 *
	 * @author mavrick@imprintnext.com
	 * @date   18 Nov 2022
	 * @return array
	 */
	private function getDefaultLanguageContent($type, $toolLang = '') {
		$languageContent = array();
		$languageInit = new Language();
		$storeId = 1;
		if ($toolLang != '') {
			$languageUrl = path('read', 'language') . 'tool/' .  'lang_'.strtolower($toolLang).'.json';
			$languageContent = json_clean_decode(fileGetContentsCurl($languageUrl), true);
		} else {
			$getLanguages = $languageInit->where('type', '=', $type)->where('store_id', '=', $storeId)->where('is_default', '=', 1);
			if ($getLanguages->count() > 0) {
				$defaultLanguage = $getLanguages->get()->toArray();
				$languageUrl = $defaultLanguage[0]['file_name'];
				$languageContent = json_clean_decode(fileGetContentsCurl($languageUrl), true);
			}
		}		
		return $languageContent;
	}

	/**
	 * Internal: Update Print method ids on order item
	 *
	 * @param $itemId  
	 * @param $customDesignId  
	 *
	 * @author mike@imprintnext.com
	 * @date   18 Jan 2023
	 * @return No
	 */
	public function updatePrintMethodsByRefId($itemId,$customDesignId) {
		$printMethodIds = [];

		if (!empty($customDesignId)) {
			$stateDesignPath = path('abs', 'design_state') . 'carts/' . $customDesignId . '.json';
			if (!file_exists($stateDesignPath)) {
				$stateDesignPath = path('abs', 'design_state') . 'predecorators/' . $customDesignId . '.json';
			}
			if (file_exists($stateDesignPath)) {
				$jsonData = json_clean_decode(file_get_contents($stateDesignPath), true);
				$sizeLoop = sizeof($jsonData['sides']);
				if (!empty($jsonData)) {
					for ($i = 0; $i < $sizeLoop; $i++) {
					    $printMetod = [];
						$designStatus = 0;
						$svgData = $jsonData['sides'][$i]['svg'];
						if ($svgData != '') {
							$designStatus = 1;
						}
						if($designStatus) {
							foreach ($jsonData['sides'][$i]['print_area'] as $profile) {
								$printMetod[] = $profile['print_method_id'];
							}
							$printMethodIds = array_unique($printMetod);
						}
					}
				}
			}
		}
		if (!empty($printMethodIds)) {
			// Update order Item meta by store end.
			$this->addPrintProfileToStoreOrderItem($itemId,$printMethodIds);
		}
	}

	/**
     * Create Reorder
     *
     * @author     steve@imprintnext.com
     * @date       21 Apr 2023
     * @param  orderId
     * @param  order item no.
     * @response   checkout url
     */
	public function createReorder($request, $response, $args)
	{
		$serverStatusCode = OPERATION_OKAY;
		$cartData = $this->storeReorder($request, $response, $args);
		return response(
			$response, ['data' => $cartData, 'status' => $serverStatusCode]
		);
	}

		/**
	 * Internal: Generate Repeat Customer Reate
	 *
	 * @param $ordersDataArr  Order details
	 *
	 * @author steve@imprintnext.com
	 * @date   10 Apr 2023
	 * @return repeat customer rate
	 */
	private function getrepeatCustomerRate($ordersDataArr) {
		$repCustomerrate = 0;
		$orderDetails = $ordersDataArr['order_details'];
		if (!empty($orderDetails)) {
			$repeatArray = [];
			foreach ($orderDetails as $value) {
				$customeId = $value['customer_id'];
				if (array_key_exists($customeId, $repeatArray)) {
					$repeatArray[$customeId] = $repeatArray[$customeId] + 1;
				} else {
					$repeatArray[$customeId] = 1;
				}
			}
			$coustomerRepeatCount = 0;
			foreach ($repeatArray as $repvalue) {
				if ($repvalue > 1) {
					$coustomerRepeatCount += 1;
				}
			}
			$res = ($coustomerRepeatCount / count($repeatArray)) * 100;
			$repCustomerrate = round($res, 2);
		}
		return $repCustomerrate;
	}

	/**
	 * Internal: Get Order Detail For UI
	 *
	 * @param $storeResponse  
	 *
	 * @author steve@imprintnext.com
	 * @date   13 APR 2022
	 * @return boolean
	 */

	 public function getOrderDetailsView($request, $response, $args, $returnType = 0) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Order Log', 'not_found'),
			'data' => [],
		];
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
		if(!isset($args['list_exclude'])){
			$args['list_exclude'] = [];
		}
		$args['ui']= 1;
		$storeResponse = $this->getStoreOrders($request, $response, $args);
		$ordersInit = new Orders();	
		
		if (!empty($args['id']) && !empty($storeResponse)) {
			//Printful Shipping status
            $IntegrationObj = new IntegrationController();
            $printfulPluginId = $IntegrationObj->getPluginId('printful');
           
			if ($printfulPluginId > 0){
				$storeResponse['order_details']['printful'] = $this->getPrintfulOrderStatus($printfulPluginId, $args['id']);				
            }			
			//shipstation Shipping status
            $shipstationPluginId = $IntegrationObj->getPluginId('ship_station');
           
			if ($shipstationPluginId > 0){
            	$storeResponse['order_details']['ship_station'] = $this->shipStationOrder($shipstationPluginId, $args['id']);				
            }
			
			/** generate base code */
			$orderId = "order-".$args['id'];
			$barCodePath =  ASSETS_PATH_W.'bar_codes/'.$orderId.'.png';
			
			if (!file_exists($barCodePath)) {
				$this->createOrderBarCode($args['id']);
			}
			

			//Get artwork status
			$ordersArtworkStatus = $ordersInit->where('order_id', $args['id']);
			$artworkStatusData = $ordersArtworkStatus->first();
			$storeResponse['order_details'] += ['po_status' => (!empty($artworkStatusData->po_status)) ? $artworkStatusData->po_status : 0];
			$storeResponse['order_details'] += ['production_status' => (!empty($artworkStatusData->production_status)) ? $artworkStatusData->production_status : 0];
			$storeResponse['order_details'] +=['barcode_url' => ASSETS_PATH_R.'bar_codes/'.$orderId.'.png'];

				
			if ($artworkStatusData->po_status == 0) {
				$storeResponse['order_details'] += ['po_status_name' => ''];
				$storeResponse['order_details'] += ['po_status_color' => ''];
			} else {
				$poStatusDetails = $this->getOrderPoStatusDetails($args['id'], $artworkStatusData->po_status, $storeId);
				$po_status_name = isset($poStatusDetails['status_name']) ? $poStatusDetails['status_name']: '';
				$po_status_color = isset($poStatusDetails['color_code']) ? $poStatusDetails['color_code']: '';
				$storeResponse['order_details'] += ['po_status_name' => $po_status_name];
				$storeResponse['order_details'] += ['po_status_color' => $po_status_color];
			}
			
			$thisOrderId = strtolower(STORE_NAME) != "shopify" ? $storeResponse['order_details']['id'] : $storeResponse['order_details']['order_number'];
			
			// Call to internal function to generate Decorate Data
			$storeResponse = $this->viewDecoratedData($request,$storeResponse, $thisOrderId, $args);
			if (empty($storeResponse['order_details']['note'])) {
				$ordersInit = new Orders();
					$ordersPoStatus = $ordersInit
					->select('quotations.quote_id as quotation_number', 'quotations.note as quotation_note')
					->join('quotations', 'orders.order_id', '=', 'quotations.order_id')
					->where('orders.order_id', $storeResponse['order_details']['id'])->first();
					$storeResponse['order_details']['notes'][0] = !empty($ordersPoStatus->quotation_note) ? $ordersPoStatus->quotation_note : "N/A";
			} else {
				$storeResponse['order_details']['notes'][0] = $storeResponse['order_details']['note'];
			}
			if (isset($args['is_return']) && $args['is_return']) {
				return $storeResponse;
			} else {
				// made a separate function for the new UI because the old structure is used in production hub and it should not be broken.
				
				//$customDesignIDs = $this->orderDesignInfoForAdminUI($storeResponse['order_details']['orders']);
				//$storeResponse['order_details']['designs'] = $customDesignIDs;
				
				$jsonResponse = [
					'status' => 1,
					'total_records' => $storeResponse['total_records'],
					'data' => $storeResponse['order_details'],
				];
			}
		}

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


	/**
	 * Internal: Get decorated Data for UI
	 *
	 * @param $storeResponse  
	 *
	 * @author steve@imprintnext.com
	 * @date   13 APR 2022
	 * @return boolean
	 */
	private function viewDecoratedData($request,$storeResponse, $thisOrderId, $args){
		$isPurchaseorder = $request->getQueryParam('isPurchaseorder') ? $request->getQueryParam('isPurchaseorder') : false;	
		$jsonContent = "";
		$designId = [];
		$notes = [];
		$storeDetails = get_store_details($request);
		$storeId = $storeDetails['store_id'] ? $storeDetails['store_id'] : 1;
		$artworkApprovalInit = new ArtworkApproval();
		foreach ($storeResponse['order_details']['orders'] as $orderDetailsKey => $orderLines) {
			
			
			foreach ($orderLines['line_items'] as $lineKey => $orderDetails) {
				
				if(!in_array('overlogo', $args['list_exclude']) && array_key_exists('overlogo_id', $orderDetails) && $orderDetails['overlogo_id'] != "" && $orderDetails['custom_design_id'] == "") {
					// If overlogo product replace store image to overlogo preview image
					$overLogoID = $orderDetails['overlogo_id'];
					$storeResponse['order_details']['orders'][$orderDetailsKey]['overlogo_id'] = $overLogoID;
					$overlogoPreviewImg = ASSETS_PATH_R . "overlogo/cartproductimage/" . $overLogoID . "/preview.jpg";
					$storeResponse['order_details']['orders'][$orderDetailsKey]['line_items'][$lineKey]['images'][0]['src'] = $overlogoPreviewImg;
					$storeResponse['order_details']['orders'][$orderDetailsKey]['line_items'][$lineKey]['images'][0]['thumbnail'] = $overlogoPreviewImg;
					//Get logo file
					$all_files = glob(ASSETS_PATH_W . "overlogo/cartproductimage/" . $overLogoID . "/*.*");
					foreach ($all_files as $filename) {
						$name = basename($filename);
						$fileNameOnly = pathinfo($filename, PATHINFO_FILENAME);
						if ($fileNameOnly != "preview") {
							$storeResponse['order_details']['orders'][$orderDetailsKey]['logo_data'] = $storeResponse['order_details']['orders'][$orderDetailsKey]['line_items'][$lineKey]['logo_data'];
							$storeResponse['order_details']['orders'][$orderDetailsKey]['logo_data'][0]['logo_url'] = ASSETS_PATH_R . "overlogo/cartproductimage/" . $overLogoID . "/" . $name;
						}
					}
				}
				$designImages = [];
				$productDecoData = [];
				$isNameAndNumber = false;
				if ($orderDetails['custom_design_id'] > 0) {
					$orderFolderDir = path('abs', 'order') . $args['id'] . '/order.json';
					$customDesignId = $orderDetails['custom_design_id'];
					$deisgnStatePath = path('abs', 'design_state') . 'carts';
					$predecoPath = path('abs', 'design_state') . 'predecorators';
					$quotationPath = path('abs', 'design_state') . 'artworks';
					$orderJsonPath = $deisgnStatePath . '/' . $customDesignId . ".json";
					$orderPredecoPath = $predecoPath . '/' . $customDesignId . ".json";
					$orderQuotationPath = $quotationPath . '/' . $customDesignId . ".json";
					
					if (file_exists($orderJsonPath)) {
						$orderJson = read_file($orderJsonPath);
						$jsonContent = json_clean_decode($orderJson, true);
					} elseif (file_exists($orderPredecoPath)) {
						$orderJson = read_file($orderPredecoPath);
						$jsonContent = json_clean_decode($orderJson, true);
					} elseif (file_exists($orderQuotationPath)) {
						$orderJson = read_file($orderQuotationPath);
						$jsonContent = json_clean_decode($orderJson, true);
					}
					$storeResponse['order_details']['orders'][$orderDetailsKey]['design_price'] = isset($jsonContent['added_price']) ? $jsonContent['added_price'] : 0;
					// code for svg configurator data fetcehd from desoginstate.json//
					$svgConfiguratorArr = [];
					if (!empty($jsonContent['configurator_svg_info'])) {
						$svgConfiguratorArr = $jsonContent['configurator_svg_info'];
					}

					if (!$isPurchaseorder && !empty($jsonContent['design_product_data'])) {
							$variantIdArr = [];
							foreach ($jsonContent['design_product_data'] as $designImage) {
								// Added for same product image for artwork
								
								if (file_exists($orderQuotationPath) || file_exists($orderPredecoPath)) {
									$designImages = [];
									
									if (!empty($designImage['design_urls'])) {
										foreach ($designImage['design_urls'] as $image) {
											$designImages[] = [
												'src' => $image,
												'thumbnail' => $image,
											];
										}
									}
								} else {
								if (($orderDetails['variant_id'] == 0 || in_array($orderDetails['variant_id'], $designImage['variant_id'])) &&
									!in_array($orderDetails['variant_id'], $variantIdArr)
								) {

									array_push($variantIdArr, $orderDetails['variant_id']);
									
									if (!empty($designImage['design_urls'])) {
										foreach ($designImage['design_urls'] as $image) {
											$designImages[] = [
												'src' => $image,
												'thumbnail' => $image,
											];
										}
									}
								}
							}
								$storeResponse['order_details']['orders'][$orderDetailsKey]['variableDecorationSize'] = isset($designImage['variable_decoration_size']) ? $designImage['variable_decoration_size'] : '';
								$storeResponse['order_details']['orders'][$orderDetailsKey]['variableDecorationUnit'] = isset($designImage['variable_decoration_unit']) ? $designImage['variable_decoration_unit'] : '';
								$storeResponse['order_details']['orders'][$orderDetailsKey]['configurator_svg_info'] = $svgConfiguratorArr;
							}
						
					}

					if (!empty($jsonContent['sides'])) {
						$i = 1;
						foreach ($jsonContent['sides'] as $sideDetailsKey => $sideDetails) {
							$configurator = [];
							
							if (isset($sideDetails['configurator']) && !empty($sideDetails['configurator'])) {
								$configurator = $sideDetails['configurator'];
							}
							$sideName = !empty($sideDetails['side_name']) ? $sideDetails['side_name'] : "";
							$isDesign = !empty($sideDetails['is_designed']) ? $sideDetails['is_designed'] : 0;
							$decorationData = [];
							
							if (!empty($sideDetails['print_area'])) {
								$j = 0;
								foreach ($sideDetails['print_area'] as $profile) {
									$digits = 3;
									$rvnUniqeNo = str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);
									$artworkPreviewUrl = '';
									$orderDwonloadObj = new OrderDownloadController();
									$filePathR = ASSETS_PATH_R . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i;
									$filePathW = ASSETS_PATH_W . 'orders/' . $thisOrderId . '/' . $orderDetails['id'] . '/side_' . $i;
									$fileStr = 'Layer_' . $j . '_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId;
									$svgPath = $filePathW . '/' . $fileStr . '.svg';
									$svgPreviewPath = $filePathW . '/' . $fileStr . '_preview.svg';
									if (array_key_exists('is_single_printfile_enabled', $profile) && $profile['is_single_printfile_enabled']) {
										$fileStr = 'single_side_' . $i . '_' . $orderDetails['id'] . '_' . $thisOrderId;
									} else if (!file_exists($svgPath) && file_exists($svgPreviewPath)) {
										$fileStr = '/' . $fileStr . '_preview';
									}
									$svgUrl = $filePathR . '/' . $fileStr . '.svg';
									$pngUrl = $filePathR . '/' . $fileStr . '.png';
									$svgPath = $filePathW . '/' . $fileStr . '.svg';
									$pngPath = $filePathW . '/' . $fileStr . '.png';
									
									if(!file_exists($svgPath) && !file_exists($pngPath)) {
										if (array_key_exists('is_single_printfile_enabled', $profile) && $profile['is_single_printfile_enabled']) {
											$previewFileName = 'single';
										} else {
											$previewFileName = 'Layer_' . $j;
										}
										$svgUrlCart = ASSETS_PATH_R . 'design_states/artwork_files/' . $customDesignId . '/side_' . $i . '/' . $previewFileName . '_side_' . $i . '_' . $customDesignId . '.svg';
										$svgUrl = (file_exists($svgUrlCart)) ? $svgUrlCart : $svgUrl;
									}
									if (!file_exists($pngPath) && in_array('png', $profile['allowed_order_formats'])) {
										$orderDwonloadObj->svgConvertToPng($pngPath, $svgPath);
									}
									$artworkPreviewUrl = (file_exists($pngPath)) ? $pngUrl : $svgUrl;
									if ($profile['isDesigned'] > 0) {
										if (in_array("png", $profile['allowed_order_formats'])) {
											$artworkPreviewUrl = $pngUrl;
										} elseif (in_array("pdf", $profile['allowed_order_formats'])) {
											$artworkPreviewUrl = $svgUrl;
										} else {
											$artworkPreviewUrl = $svgUrl;
										}
										$decorationData[] = [
											'decoration_name' => isset($profile['name']) ? $profile['name'] : "",
											'print_area_id' => $profile['print_area']['id'],
											'print_area_name' => $profile['print_area']['name'],
											'print_profile_id' => $profile['print_method_id'],
											'print_profile_name' => $profile['print_method_name'],
											'print_unit' => $sideDetails['print_unit'],
											'print_area_height' => $profile['print_area']['height'],
											'print_area_width' => $profile['print_area']['width'],
											'design_width' => isset($profile['design_width']) ? $profile['design_width'] : "",
											'design_height' => isset($profile['design_height']) ? $profile['design_height'] : "",
											//'svg_url' => $svgUrl,
											'svg_artwork_url' => $svgUrl,
											'png_url' => $pngUrl,
											'layer' => $j,
											'used_colors' => $profile['used_colors'] ? $profile['used_colors'] : [],
											'used_patterns' => $profile['used_patterns'] ? $profile['used_patterns'] : [],
											'x_location' => isset($profile['design_x']) ? $profile['design_x'] : "",
											'y_location' => isset($profile['design_y']) ? $profile['design_y'] : "",
											'name_number_font_details' => isset($profile['name_number_font_details']) ? $profile['name_number_font_details'] : [],
											'rotate' => isset($jsonContent['layer_data'][$sideDetailsKey][$j]['rotate']) ? $jsonContent['layer_data'][$sideDetailsKey][$j]['rotate'] : false,
											'artwork_coordinates' => isset($profile['artwork_coordinates']) ? $profile['artwork_coordinates'] : [],
											'allowed_order_format' => $profile['allowed_order_formats'],
											'artwork_preview_url' => $artworkPreviewUrl,
										];
									}
									$j++;
								}
							}
							$productDecoData[] = [
								'is_design' => $isDesign,
								'name' => $sideName,
								'decoration_data' => $decorationData,
								'configurator' => $configurator,
								'stickerInfo' => $sideDetails['stickerInfo'],
							];
							$i++;
						}
					}
					if (!empty($jsonContent['name_number'])) {
						$isNameAndNumber = true;
					}
					if (!empty($jsonContent['rotate_angle'])) {
						$rotateAngle = $jsonContent['rotate_angle'];
					}
				} elseif ($orderDetails['custom_design_id'] < 0) {
					$orderFolderDir = path('abs', 'order') . $thisOrderId . '/order.json';
					if (is_file($orderFolderDir)) {
						$orderJson = read_file($orderFolderDir);
						$jsonContent = json_clean_decode($orderJson, true);
						$orderItemArr = $jsonContent['order_details']['order_items'];
						$itemId = $orderDetails['id'];
						$itemArr = array_filter($orderItemArr, function ($item) use ($itemId) {
							return ($item['item_id'] == $itemId);
						});
						$itemArr = $itemArr[array_keys($itemArr)[0]];
						$filesDataArr = $itemArr['file_data'];
						
						if (!empty($filesDataArr)) {
							foreach ($filesDataArr as $files) {
								$decorationData = [];
								foreach ($files['decoration_area'] as $decorationArea) {
									$designImages[] = [
										'src' => $decorationArea['upload_preview_url'],
										'thumbnail' => $decorationArea['upload_preview_url'],
									];
									$extension = pathinfo(parse_url($decorationArea['upload_design_url'], PHP_URL_PATH), PATHINFO_EXTENSION);
									$fileFormat = array($extension);
									$decorationData[] = [
										'decoration_name' => $decorationArea['decoration_area'],
										'print_area_id' => $decorationArea['print_area_id'],
										'print_area_name' => $decorationArea['print_area_name'],
										'print_profile_id' => $decorationArea['print_method_id'],
										'print_profile_name' => $decorationArea['print_methods'],
										'print_unit' => $decorationArea['measurement_unit'],
										'print_area_height' => $decorationArea['height'],
										'print_area_width' => $decorationArea['width'],
										'design_width' => $decorationArea['design_width'],
										'design_height' => $decorationArea['design_height'],
										//'svg_url' => $decorationArea['upload_design_url'],
										'svg_artwork_url' => $decorationArea['upload_design_url'],
										'png_url' => $decorationArea['upload_design_url'],
										'allowed_order_format' => $fileFormat,
										'artwork_preview_url' => $decorationArea['upload_design_url'],
									];
								}
								$productDecoData[] = [
									'is_design' => 1,
									'name' => $files['side_name'],
									'decoration_data' => $decorationData,
								];
							}
						}
					}
				}
				$storeResponse['order_details']['orders'][$orderDetailsKey] += [
					'decoration_settings_data' => $productDecoData,
				];
				
				// if (!in_array('getProductDescription', $args['list_exclude'])) {
					//Get product description
					// $productId = $storeResponse['order_details']['orders'][$orderDetailsKey]['product_id'];
					// $productsControllerInit = new ProductsController();
					// $storeResponse['order_details']['orders'][$orderDetailsKey]['line_items'][$lineKey] += [
					// 	'product_description' => $productsControllerInit->getProductDescription($productId),
					// ];
				// }
				
				if (!empty($designImages) && strtolower(STORE_NAME) != "shopify") {
					$storeResponse['order_details']['orders'][$orderDetailsKey]['line_items'][$lineKey]['images'] = $designImages;
				}
				
				if (empty($designId) || !in_array($customDesignId, $designId)) {
					if (!empty($jsonContent)) {
						$notes[] = $jsonContent['notes'];
					}
					$designId[] = $customDesignId;
				}
				
				if (strtolower(STORE_NAME) == "shopify") {
					$ordersInit = new Orders();
					$ordersStatus = $ordersInit->where('order_id', $storeResponse['order_details']['id'])->first();
					$storeResponse['order_details']['status'] = (!empty($ordersStatus->order_status)) ? $ordersStatus->order_status : 'received';
				}
				
				$poStatus = $this->getOrderPoStatus($args['id'], $orderDetails['id'], $storeId);
				$storeResponse['order_details']['orders'][$orderDetailsKey]['line_items'][$lineKey]['po_status'] = $poStatus;
				$storeResponse['order_details']['orders'][$orderDetailsKey]['design_note'] = (!empty($jsonContent) && isset($jsonContent['notes'])) ? $jsonContent['notes'] : '';
				$storeResponse['order_details']['orders'][$orderDetailsKey]['line_items'][$lineKey]['store_image'] = $orderDetails['images'];
			}
			//Order artwork approval section
			$artworkApprovalData = [];
			$artworkApprovalData['show_edit_artwork_btn'] = 1;
			if (strtolower(STORE_NAME) == "shopify") {
				$getOrderId = $args['id'];
			} else {
				$getOrderId = $thisOrderId;
			}
			$checkForApproval = $artworkApprovalInit->select('*', DB::raw("(SELECT count(xe_id) FROM `artwork_approval_conversations` WHERE order_artwork_id = artwork_approval.xe_id AND user_type = 'customer' AND seen_flag = 1) as total_conv_count"))->where(['order_id' => $getOrderId, 'old_ref_id' => $customDesignId]);
			if ($checkForApproval->count() > 0) {
				$approvalData = $checkForApproval->first()->toArray();
				$artworkApprovalData['show_edit_artwork_btn'] = 0;
				$artworkApprovalData['status'] = $approvalData['status'];
				if ($approvalData['status'] == 0) {
					$statusText = 'Artwork updated';
					$statuSlug = 'artwork_updated';
					$statusColor = '#cef6e6';
				} elseif ($approvalData['status'] == 1) {
					$statusText = 'Sent for approval';
					$statuSlug = 'sent_for_approval';
					$statusColor = '#d9f0ff';
				} elseif($approvalData['status'] == 2) {
					$statusText = 'Approved';
					$statuSlug = 'approved';
					$statusColor = '#aef5cf';
				} elseif($approvalData['status'] == 3) {
					$statusText = 'Rejected';
					$statuSlug = 'rejected';
					$statusColor = '#ffdfdf';
				} else {
					$statusText = '';
					$statuSlug = '';
					$statusColor = '';
				}
				$artworkApprovalData['status_text'] = $statusText;
				$artworkApprovalData['status_slug'] = $statuSlug;
				$artworkApprovalData['status_color'] = $statusColor;
				$artworkApprovalData['order_artwork_id'] = $approvalData['xe_id'];
				$token = 'order_id=' . $getOrderId. '&order_artwork_id='.$approvalData['xe_id'].'&store_id='. $storeId;
                $token = base64_encode($token);
                $publicUrl = API_URL . 'quotation/art-work?token=' . $token . '&artwork_type=order';
				$artworkApprovalData['public_url'] = $publicUrl;
				$artworkApprovalData['conversation_count'] = $approvalData['total_conv_count'];
			}
			$storeResponse['order_details']['orders'][$orderDetailsKey]['artwork_approval'] = $artworkApprovalData;
			$storeResponse['order_details']['orders'][$orderDetailsKey]['is_name_and_number'] = $isNameAndNumber;
			$storeResponse['order_details']['orders'][$orderDetailsKey]['rotate_angle'] = $rotateAngle;
		}		
		return $storeResponse;
	}

	/**
	 * Internal: Save and get order data in memcached
	 *
	 * @param $storeResponse  
	 *
	 * @author steve@imprintnext.com
	 * @date   13 JUN 2024
	 * @return boolean
	 */

	public function getStoreOrders($request, $response, $args){
		if(!empty($args) and isset($args['id'])){
			$orderId = $args['id'];
			$ui = 0;
			if(isset($args['ui'])){
				$ui = $args['ui'];
			}
			$storeId = 1;
			if(isset($args['store_id'])){
				$storeId = $args['store_id'];
			}else{
				$storeDetails = get_store_details($request);
				$storeId = $storeDetails['store_id'];
			}	
			//GET MEMCACHEDATA
			$memcacheData = [];
			if (IS_MEMCACHE) {
				//MEMCACHED KEY
				 $thisCacheKey = "orders" . "_id" . $orderId . "_ui" . $ui."_store". $storeId;
				//Register MEMCACHED KEY in Local Cache
				$this->createUpdateMemCacheGroup('orders', $thisCacheKey, 'SET');	
				$memcacheData = $this->memcache("get", $thisCacheKey);
				if(empty($memcacheData)){
					$storeResponse = $this->getOrders($request, $response, $args);
					//SET IN MEMCACHED
					if (IS_MEMCACHE and isset($thisCacheKey)) {
						$this->memcache("set", $thisCacheKey, $storeResponse);
					}
				}else{
					$storeResponse = $memcacheData;
				}
			}else {
				$storeResponse = $this->getOrders($request, $response, $args);
			}
		}else{
			$storeResponse = $this->getOrders($request, $response, $args);
		}	
        return $storeResponse;
    }
	/**
	 * Get: Get Total Orders
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 * @param $args     Slim's Argument parameters
	 *
	 * @author mavrick@imprintnext.com
	 * @date   10 Jan 2025
	 * @return Total Orders in Json format
	 */
	public function listOrders($request, $response, $args, $returnType = 0) {
		$jsonResponse = [
			'status' => 0,
			'message' => 'Operation not allowed',
			'data' => []
		];
		$userObj = new UsersController();
		$userStatus =  $userObj->checkAuthorization($request, $response, $args);
		if($userStatus) {
			$jsonResponse = $this->getOrderList($request, $response, $args, 1);
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => OPERATION_OKAY
		]);
	}
	/**
	 * Internal: Get Order Detail For API
	 *
	 * @param $storeResponse  
	 *
	 *
	 * @author mavrick@imprintnext.com
	 * @date   10 Jan 2025
	 * @return Order details in Json format
	 */
	public function getSingleOrderDetails($request, $response, $args, $returnType = 0) {
		$jsonResponse = [
			'status' => 0,
			'message' => 'Operation not allowed',
			'data' => []
		];
		$userObj = new UsersController();
		$userStatus = $userObj->checkAuthorization($request, $response, $args);
		if($userStatus){
			$jsonResponse	= $this->getOrderDetailsView($request, $response, $args, 1);
		}
		return response($response, [
			'data' => $jsonResponse, 'status' => OPERATION_OKAY
		]);
	}
}