<?php
/**
 * Manage BarCode
 *
 * PHP version 5.6
 *
 * @category  BarCode
 * @package   Bar_Code
 * @author    Soumya <soumyas@riaxe.com>
 * @copyright 2022-2023 Riaxe Systems
 * @license   http://www.php.net/license/3_0.txt  PHP License 3.0
 * @link      http://inkxe-v10.inkxe.io/xetool/admin
 */

namespace App\Modules\BarCode\Controllers;
use App\Components\Controllers\Component as ParentController;
use App\Modules\Settings\Models\Setting;
use App\Modules\BarCode\Models\Barcodes;
use App\Modules\Orders\Controllers\OrdersController;
use App\Modules\Productions\Models\ProductionStatus;
use App\Modules\Orders\Models\Orders;
use App\Modules\Productions\Models\ProductionJobs;

/**
 * BarCode Controller
 *
 * @category BarCode
 * @package  Bar_Code
 * @author   Soumya <soumyas@riaxe.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://inkxe-v10.inkxe.io/xetool/admin
 */
class BarCodeController extends ParentController {
	
	/**
	 * Define image upload path
	 **/
	public function __construct() {
		$barCodePath =  ASSETS_PATH_W.'bar_codes';
		if (!is_dir($barCodePath)) {
    		mkdir($barCodePath, 0777, true);
		}
	}

	/**
	 * GET: Get BarCode Settings
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@riaxe.com
	 * @date   29 March 2022
	 * @return json response
	 */
	public function getBarCodeSetting($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Vendor', 'error'),
		];
		$storeId = $request->getQueryParam('store_id') ? $request->getQueryParam('store_id') : 1;
		$settingsType = $request->getQueryParam('setting_type') ? $request->getQueryParam('setting_type') : 'barcode_settings';
		$settingInit = new Setting();
		$getSettings = $settingInit->select('setting_key', 'setting_value')
			->where(['setting_key' => $settingsType,'store_id' => $storeId]);
		if($getSettings->count() > 0) {
			$getBarCodeSettingData =  $getSettings->get()->first()->toArray();
			$getBarCodeSettingDataArray =  json_decode($getBarCodeSettingData['setting_value'], 1);
			$jsonResponse = [
				'status' => 1,
				'data' => $getBarCodeSettingDataArray ? $getBarCodeSettingDataArray:[],
			];
		}
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * SAVE: Save BarCode Settings
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@riaxe.com
	 * @date   30 March 2022
	 * @return json response
	 */
	public function saveBarCodeSetting($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('BarCode', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$settingsType = $allPostPutVars['setting_key'];
		$storeId = $allPostPutVars['store_id'] ? $allPostPutVars['store_id'] : 1;
		$settingValue = $allPostPutVars['setting_value'];
		if($settingsType == "barcode_settings") {
			$settingInit = new Setting();
			$getSettings = $settingInit->where(['setting_key' => $settingsType,'store_id' => $storeId]);
			if($getSettings->count() > 0) {
				$updateData = ['setting_value' => $settingValue , 'type' => 0];
				$updateSettingsData = new Setting();
				$updateSettingsData->where(['setting_key' => $settingsType , 'store_id' => $storeId])->update($updateData);
				$jsonResponse = [
					'status' => 1,
					'message' => 'Record updated successfully',
				];
			} else {
				$saveData = [ 
					'setting_key' => $settingsType , 
					'setting_value' => $settingValue , 
					'type' => 0 , 
					'store_id' =>$storeId
				];
				$saveSettingsData = new Setting($saveData);
				$saveSettingsData->save();
				$jsonResponse = [
					'status' => 1,
					'message' => 'Record saved into application',
				];
			}
		}
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * GET: Get BarCode Settings
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@riaxe.com
	 * @date   30 March 2022
	 * @return json response
	 */
	public function getBarcodeModuleData($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('BarCode', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$storeId = $allPostPutVars['store_id'] ? $allPostPutVars['store_id'] : 1;
		$barcodeArray = [];
		$barCodesInit = new BarCodes();
		$getBarCodeData = $barCodesInit
		->join('production_hub_modules', 'barcodes.module_id', '=', 'production_hub_modules.xe_id')
		->select(
			'barcodes.module_id', 'barcodes.store_id', 'production_hub_modules.xe_id', 'production_hub_modules.name'
		)->where(['barcodes.store_id' => $storeId])->groupBy('barcodes.module_id')->groupBy('barcodes.store_id')->groupBy('production_hub_modules.xe_id')->groupBy('production_hub_modules.name');
		if($getBarCodeData->count() > 0) {
			$getBarCodeDataArray =  $getBarCodeData->get()->toArray();
			foreach($getBarCodeDataArray as $key => $value) {
				$barcodeArray[$key]['module_id'] = $value['module_id'];
				$barcodeArray[$key]['module_name'] = $value['name'];
				$barcodeArray[$key]['module_data'] = $this->getModuleData($value['module_id'], $storeId);
			}
			$jsonResponse = [
				'status' => 1,
				'data' => $barcodeArray,
			];
			
		}
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode], 1
		);
	}

	/**
	 * GET: Module Data
	 *
	 * @param $moduleId
	 * @param $storeId
	 *
	 * @author soumyas@riaxe.com
	 * @date   30 March 2022
	 * @return Array
	 */
	private function getModuleData($moduleId , $storeId) {
		$barCodeUrl =  ASSETS_PATH_R.'bar_codes/';
		$moduleDataArray = [];
		$barCodesInit = new BarCodes();
		$getBarCodeData = $barCodesInit->where(['module_id' => $moduleId , 'store_id' => $storeId , 'is_active' => 1]);
		if($getBarCodeData->count() > 0) {
			$moduleDataArray =  $getBarCodeData->get()->toArray();
			foreach($moduleDataArray as $key => $value) {
				$moduleDataArray[$key]['barcode_image'] = $barCodeUrl.$value['barcode_image'];
				if($value['module_id'] == 4) {
					$moduleDataArray[$key]['color_code'] = $this->getProductionStatusData($value['slug'] , $storeId);
				}
			}
		}
		return $moduleDataArray;
	}
	/**
	 * GET: Get BarCode Settings
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@riaxe.com
	 * @date   31 March 2022
	 * @return json response
	 */
	public function printBarCode($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('BarCode', 'error'),
		];
		$barCodePath =  ASSETS_PATH_W.'bar_codes/';
		$pdfFileName = getRandom();
		if (!file_exists($proofPath)) {
    		mkdir($barCodePath, 0777, true);
		}
		$defaultWidth = 100;
		$margin = 0;
		$allPostPutVars = $request->getParsedBody();
		$barCodeJsonData =  $allPostPutVars['bar_code_data'];
		$storeId = $allPostPutVars['store_id'] ? $allPostPutVars['store_id']:1;
		$settingsType = $allPostPutVars['setting_type'] ? $allPostPutVars['setting_type']:"barcode_settings";
		$printArray =  json_clean_decode($barCodeJsonData);
		$perColumn = 1;
		$labelFont = "5px";
		$fontSize = "10px";
		$margin = "10px";
		$moduleArray = ['order' => 'Order Processing Barcodes' , 'production' => 'Production Processing Barcodes']; 
		/*get setting data*/
		$settingInit = new Setting();
		$getSettings = $settingInit->select('setting_key', 'setting_value')
			->where(['setting_key' => $settingsType,'store_id' => $storeId]);
		if($getSettings->count() > 0) {
			$getSettingsData =  $getSettings->get()->first()->toArray();
			$getSettingsDataArray =  json_decode($getSettingsData['setting_value'], 1);
			$columnsData =  $getSettingsDataArray['columns'];
			$labelFontSizeData =  $getSettingsDataArray['label_font_size'];
			$fontSizeData =  $getSettingsDataArray['font_size'];
			$marginData =  $getSettingsDataArray['margin'];
			/*for column*/
			$getActiveColumnKey = array_search(1, array_column($columnsData, 'is_active'));
			$getSingleColumn =  $columnsData[$getActiveColumnKey];
			$perColumn = $getSingleColumn['value'];
			
			/*for label_font_size*/
			$getActiveLabelFontKey = array_search(1, array_column($labelFontSizeData, 'is_active'));
			$getSingleFontLabel =  $labelFontSizeData[$getActiveLabelFontKey];
			$labelFont = $getSingleFontLabel['value'];

			/*for font_size*/
			$getfontSizeKey = array_search(1, array_column($fontSizeData, 'is_active'));
			$getSingleFontSize =  $fontSizeData[$getfontSizeKey];
			$fontSize =  $getSingleFontSize['value'];
			/*for margin*/
			$getMargineKey = array_search(1, array_column($marginData, 'is_active'));
			$getSingleMargin = $marginData[$getMargineKey];
			$margin =  $getSingleMargin['value'];
		}
		if(!empty($printArray)) {
			$defaultWidth = $defaultWidth-$margin;
	    	$tdWidth = round($defaultWidth/$perColumn).'%';
	    	$html = '';
			$html.='<html>';
			$html.='<head>';
			$html.='</head>';
		    $html.='<body>';
		    /*main table start*/
		    $html.='<table style="width:100%">';
		    $html.='<tr>';
		    $html.='<td style="width:100%">';
		    /*outer loop*/
		    foreach($printArray as $value) {
				if(!empty($value['module_data'])) {
					$moduleName =  strtolower($value['module_name']);
		    		$html.='<table style="width:100%;margin-bottom:'.$margin.'">';
		    		$html.='<tr>';
		    		$html.='<td align="right" style="font-size:'.$fontSize.';text-align:left;font-weight:bold;padding-bottom:15px">'.$moduleArray[$moduleName].'</td><td></td>';
		    		$html.='</tr>';
		    		$colCount = 1;
		    		$moduleData =  $value['module_data'];
		    		$totalRow = ceil(count($moduleData) / $perColumn);
		    		/*inner loop start*/
					for ($i=1; $i <= $totalRow; $i++) {
						$html.='<tr style="'.$i.'">';
						for ($j=1; $j <= $perColumn; $j++) {
							if (count($moduleData) >= $colCount) {
								$barCodeImageUrl = $moduleData[$colCount-1]['barcode_image'];
								$name = $moduleData[$colCount-1]['name'];
								$html.='<td style="width:'.$tdWidth.';padding-bottom:'.$margin.'">'; 
								/* inner table */
								if($perColumn == 1) {
									$html.='<table  style="width:100%">';
									$imageAlign="text-align:center";
								} else {
									$html.='<table>';
									$imageAlign = '';
								}
								$html.='<tr><td style="'.$imageAlign.'"><img style="width: auto;height:auto" src="'.$barCodeImageUrl.'" /></td></tr>';
								$html.='<tr><td align="center" style="text-align : center"><span><b style="font-size: '.$labelFont.'">'.$name.'</b></span></td></tr>';
								$html.='</table>';
								$html.='</td>'; 
							}
							$colCount++;
						}
						if ($j/count($moduleData)) {
							$html.='</tr>';
						}
					}
		    	$html.='</table>';
				}
			}
		    $html.='</td>';
		    $html.='</tr>';
		    /*inner loop*/
		    $html.='</table>';
		    /*main table end*/
		    $html.='</body>';
	    	$html.='</html>';
	    	$fileNames = create_tcpdf($html, $barCodePath, $pdfFileName, 'English');
	    	$fileAbsolutePath =  $barCodePath.$fileNames;
	    	if(file_exists($fileAbsolutePath)) {
	    		$jsonResponse = ['status' => 1 , 'data' => [ 'file_url' => ASSETS_PATH_R.'bar_codes/'.$fileNames ] ];
	    	}
		}
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	
	/**
	 * Get: Production status color code
	 *
	 * @param $slug 
	 * @param $storeId 
	 * @param $moduleName 
	*
	 * @author soumyas@riaxe.com
	 * @date   04 April 2022
	 * @return String
	 */
	public function getProductionStatusData($slug , $storeId) {
		$colorCode = '';
		$statusInit = new ProductionStatus();
		$getStatusData =  $statusInit->select('color_code')->where('store_id' , '=', $storeId)->where('slug' , '=' , str_replace('job_status_', '', $slug));
		if($getStatusData->count() > 0) {
			$statusArray =  $getStatusData->first()->toArray();
			$colorCode = $statusArray['color_code'] ? $statusArray['color_code']:'';
		}
		return $colorCode;
	}
	/**
	 * GET: BarCode Details
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@riaxe.com
	 * @date   29 March 2022
	 * @return json response
	 */
	public function getBarCodeNumberDetails($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('BarCode', 'error'),
		];
		$barcodeNumber = $request->getQueryParam('barcode_number') ? $request->getQueryParam('barcode_number'):'';
		$storeId = $request->getQueryParam('store_id') ? $request->getQueryParam('store_id') : 1;
		$jobId = $request->getQueryParam('job_id') ? $request->getQueryParam('job_id') : '';
		$isOrderStatus = false;
		$barCodeResposne = [];
		if(!empty($barcodeNumber) && isset($barcodeNumber) ) {
			$isBarcode = 0;
			$barCodesInit = new BarCodes();
			$getBarCode = $barCodesInit->where(['barcode_number' => $barcodeNumber , 'store_id' => $storeId]);
			if($getBarCode->count() > 0) {
				$isBarcode = 1;
				$getBarCodeData =  $getBarCode->first()->toArray();
				$slug = $getBarCodeData['slug'];
				$moduleId = $getBarCodeData['module_id'];
				$barCodeResposne = ['slug' => $slug , 'module_id' => $moduleId , 'store_id'=> $storeId ];
				$statusInit = new ProductionStatus();
				$getStatusData =  $statusInit->select('color_code')->where('store_id' , '=', $storeId)->where('slug' , '=' ,  $slug);
				if($getStatusData->count() > 0) {
					$barCodeResposne+=['is_production' => 1]; 
				}
				$jsonResponse = ['status' => 1 , 'data' => $barCodeResposne ];
			}
			if($isBarcode == 0 && empty($jobId)) {
				$ordersInit = new Orders();
				$getSingleOrder = $ordersInit->where(['order_id' => $barcodeNumber , 'store_id' => $storeId]);
				if($getSingleOrder->count() > 0) {
					$orderResposne = ['slug' => "order" , 'module_id' => 2 , 'order_no'=> $barcodeNumber , 'store_id' => $storeId ];
					$jsonResponse = ['status' => 1 , 'data' => $orderResposne ];
				}
			}
		}
		if(!empty($jobId)) {
			$productionJobsInit =  new ProductionJobs();
			$getproductionJobs =  $productionJobsInit->where(['job_id' => $jobId , 'store_id' => $storeId]);
			if($getproductionJobs->count() > 0) {
				$getproductionJobData =  $getproductionJobs->first()->toArray();
				$jobXeid =  $getproductionJobData['xe_id'];
				$productionResposne = ['slug' => "production" , 'module_id' => 4, 'xe_id' => $jobXeid];
				$jsonResponse = ['status' => 1 , 'data' => $productionResposne ];
			}
		}
		if($moduleId == 2) {
			$orderObj = new OrdersController();
			$orderStatus =  $orderObj->getDefaultOrderStatuses($storeId);
			foreach ($orderStatus as $value) {
				$slugKey =  trim(strtolower(str_replace(' ', '_', $value['key'])));
				if($slug == $slugKey) {
					$isOrderStatus =true;
					$jsonResponse['data']['slug'] = $value['key'];
					break;
				}
			}
			$jsonResponse['data']['is_order_status'] = $isOrderStatus;
		}
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	/**
	 * SAVE: Save Order status
	 *
	 * @param $request  Slim's Request object
	 * @param $response Slim's Response object
	 *
	 * @author soumyas@riaxe.com
	 * @date   30 March 2022
	 * @return json response
	 */
	public function importOrderStatus($request, $response, $args) {
		$serverStatusCode = OPERATION_OKAY;
		$jsonResponse = [
			'status' => 0,
			'message' => message('Import order status', 'error'),
		];
		$allPostPutVars = $request->getParsedBody();
		$storeId = $allPostPutVars['store_id'] ? $allPostPutVars['store_id'] : 1;
		$orderObj = new OrdersController();
		$orderStatus =  $orderObj->getDefaultOrderStatuses($storeId);
		$importStatusCount = 0;
		if(!empty($orderStatus)) {
			$barCodesInit = new BarCodes();
			foreach($orderStatus as  $orderValue) {
				$name = "Change order status to ". $orderValue['value'];
				$key =  trim(strtolower(str_replace(' ', '_', $orderValue['key'])));
				$randomNumber =  trim(getRandom());
				$getBarCodeData = $barCodesInit->where(['slug' => $key , 'store_id' => $storeId , 'module_id' => 2]);
				if($getBarCodeData->count() == 0) {
					$saveData = ['name' => $name , 'slug' => $key , 'module_id' => 2 , 'barcode_number' => $randomNumber, 'barcode_image' => $randomNumber.'.png' , 'store_id' => $storeId];
					$barCodesSaveInit = new BarCodes($saveData);
					$barCodesSaveInit->save();
					$lastInsertId = $barCodesSaveInit->xe_id;
					if($lastInsertId > 0) {
						$barCodePath =  ASSETS_PATH_W.'bar_codes/'.$randomNumber.'.png';
						$barcode = generate_barcode($randomNumber);
						file_put_contents($barCodePath, $barcode);
						++$importStatusCount;
					}
				}
			}
			if($importStatusCount > 0) {
				$jsonResponse = [
					'status' => 1,
					'message' => "Order status barcodes generated successfully.",
				];
			} else {
				$jsonResponse = [
					'status' => 0,
					'message' => "Already generated",
				];
			}
		}
		return response(
			$response, ['data' => $jsonResponse, 'status' => $serverStatusCode]
		);
	}
	
}
