<?php

namespace App\Http\Controllers\v2019;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\authentication;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Auth\User;
use App\Http\Controllers\Action\Common;
use Cookie;

class PricesController extends Controller
{
	public $appType = 'SM';
	public function __construct(Request $request)
	{
		if ($request->has('debug') && $request->input('debug') == true) {
			$this->debug = true;
		}
		if ($request->has('appType') && $request->input('appType') == true) {
			$this->appType = $request->input('appType');
		} elseif ($request->has('filters')) {
			$filter = $request->input('filters');
			if (!empty($filter['app_type'])) {
				$this->appType = 'CM';
			}
		} else if ($request->has('app_type') && $request->input('app_type') == true) {
			$this->appType = $request->input('app_type');
		}
	}
	public function indianPriceCategories(Request $request)
	{
		if ('CM' == $this->appType)
			$filename = "https://www.steelmint.com/indianpriceCats_coal.json";
		else
			$filename = "https://www.steelmint.com/indianpriceCatsBM.json";

		$json_data =  file_get_contents($filename);
		return $json_data;
		//remove the market wise selection , as per developer requirement 
		/*if($request->has('selected_market') && $request->input('selected_market') != '') 
            $selected_market = $request->input('selected_market');
            
        if($selected_market!=''){
            $data_array = json_decode($json_data, true);           
            return json_encode($data_array[$selected_market],JSON_UNESCAPED_SLASHES);
        }else{
            return $json_data;
        }*/
	}

	public function getPricesSearch(Request $request)
	{


		if ($request->has('filters')) {
			//$filters = $request->input('filters');
			$sterm = '';
		} elseif ($request->has('sterm'))
			$sterm = strtolower($request->input('sterm'));
		else
			return new JsonResponse(array("status" => array("code" => 2100, "message" => "Search term missing!")));

		if ($request->has('sectionType'))
			$sectionType = strtolower($request->input('sectionType'));
		else
			$sectionType = '';

		$filters = array();
		if ($request->has('filters') && !empty($request->input('filters')))
			$filters = $request->input('filters');

		$result = \ApiQuery::getPricesSearchRows($sterm, $sectionType, $filters);
		$code = 1001;
		$message = "Success";

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}
	public function getPricesVendorAPI(Request $request)
	{
		//insert - request log starts
		$vendorData = array();

		$vendorData['endpoint'] = $request->fullUrl(); // Get the current endpoint
		$vendorData['request_json'] = json_encode($request->all());
		$vendorData['request_at'] = date("Y-m-d H:i:s");
		// Capture the 'api_key' input if it exists
		if ($request->has('api_key')) {
			$vendorData['api_key'] = $request->input('api_key');
		}
		// Capture the 'fromdate' input if it exists
		if ($request->has('fromdate')) {
			$vendorData['fromdate'] = $request->input('fromdate');
		}
		// Capture the 'todate' input if it exists
		if ($request->has('todate')) {
			$vendorData['todate'] = $request->input('todate');
		}
		// Capture the 'commodityID' input if it exists
		if ($request->has('commodityID')) {
			$vendorData['commodityID'] = $request->input('commodityID');
		}
		// Capture the 'regionID' input if it exists
		if ($request->has('regionID')) {
			$vendorData['regionID'] = $request->input('regionID');
		}
		// Insert the data into the 'tbl_vendor_api_history' table and get the inserted ID
		$comparisonId = DB::table('tbl_vendor_api_history')->insertGetId($vendorData);
		//insert  request log end 

		if ($request->has('api_key')) {
			$fromdate = '';
			$todate = '';
			$commodityIDSubscribedTo = '';
			$prices_assessments_to_show = '';
			$commodityIDFilter = '';
			$regionIDFilter = '';
			$appType = 'SM';

			if (!$request->has('fromdate') || empty($request->input('fromdate')) || !$request->has('todate') || empty($request->input('todate'))) {
				$code = 2001;
				$message = "Both fromdate and todate are mandatory for calling API";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}
			$fromdate = $request->input('fromdate');
			$todate = $request->input('todate');

			if ($fromdate > $todate) {
				$code = 2001;
				$message = "To date cannot be older than from date in the request.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			$str_diff = strtotime($todate) - (strtotime($fromdate));
			$dateDiff_inDays = floor($str_diff / 3600 / 24);
			if (($dateDiff_inDays) > 6) {
				$code = 2001;
				$message = "You cannot fetch data for more than 7 days at a time.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			$api_key = $request->input('api_key');
			$api_key_dtls =
				DB::table('tbl_customized_apis')
				->select(array('considerTableName', 'enddate', 'prices_assessments_to_show', 'showDataFrom', 'consider_all_assessments', 'commodityIds', 'f_market'))
				->where("api_key", "=", $api_key)
				->where("enddate", ">=", date("Y-m-d"))
				->where("startdate", "<=", date("Y-m-d"))
				->get();
			//dd(DB::getQueryLog());
			//print_r($api_key_dtls);
			if (count($api_key_dtls) == 0) {
				$code = 2001;
				$message = "The API key is invalid or it has expired.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			} else {
				if ($request->has('appType') && !empty($request->input('appType')))
					$appType = $request->input('appType');

				if ($fromdate < $api_key_dtls[0]['showDataFrom']) {
					$code = 2001;
					$message = "You are not authorized to view price data older than " . $api_key_dtls[0]['showDataFrom'] . ".";
					return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
				}

				$considerTableName = $api_key_dtls[0]['considerTableName'];
				$consider_all_assessments = $api_key_dtls[0]['consider_all_assessments'];

				if (isset($api_key_dtls[0]['commodityIds'])) {
					$commodityIDSubscribedTo = $api_key_dtls[0]['commodityIds'];
				}

				if (isset($api_key_dtls[0]['prices_assessments_to_show'])) {
					$prices_assessments_to_show = $api_key_dtls[0]['prices_assessments_to_show'];
				}

				if (isset($api_key_dtls[0]['f_market'])) {
					$f_market = $api_key_dtls[0]['f_market'];
				}

				if ($request->has('commodityID') && !empty($request->input('commodityID')))
					$commodityIDFilter = $request->input('commodityID');

				if ($request->has('regionID') && !empty($request->input('regionID')))
					$regionIDFilter = $request->input('regionID');
				$result = \ApiQuery::getPricesRowsVendorAPI($fromdate, $todate, $commodityIDSubscribedTo, $prices_assessments_to_show, $commodityIDFilter, $regionIDFilter, $considerTableName, $consider_all_assessments, $appType, $api_key, $f_market);
				return new JsonResponse(array("status" => array("code" => 1001, "message" => "Success"), "data" => $result));
			}
		} else {
			$code = 2001;
			$message = "API Key is mandatory in request";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}
	}

	public function getPrices(Request $request)
	{
		//throw data for reliance
		if ($request->has('api_key')) {
			$api_key = $request->input('api_key');

			//check if api_key is valid	
			//DB::enableQueryLog(); 
			$api_key_dtls =
				DB::table('tbl_customized_apis')
				->select(array('considerTableName', 'enddate', 'prices_assessments_to_show', 'showDataFrom', 'consider_all_assessments', 'commodityIds'))
				->where("api_key", "=", $api_key)
				->where("enddate", ">=", date("Y-m-d"))
				->get();
			//dd(DB::getQueryLog());
			//print_r($api_key_dtls);
			if (count($api_key_dtls) == 0) {
				$code = 2001;
				$message = "api key is invalid or it has expired.";

				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			} else {
				$currency = "Currency";
				$memid = 116686;
				$filters = array();
				$fromdate = '';
				$todate = '';

				if ($request->has('filters') && !empty($request->input('filters')))
					$filters = $request->input('filters');

				if (isset($filters['fromdate']) && $filters['fromdate'] != '')
					$fromdate = $filters['fromdate'];
				if (isset($filters['todate']) && $filters['todate'] != '')
					$todate = $filters['todate'];

				//				$filters = array();
				//				if($request->has('filters') && !empty($request->input('filters')))
				//					$filters = $request->input('filters');
				$prices_assessments_to_show = $api_key_dtls[0]['prices_assessments_to_show'];
				$trade_type = $api_key_dtls[0]['trade_type'];

				$consider_all_assessments = $api_key_dtls[0]['consider_all_assessments'];
				if ($consider_all_assessments == 'y' && $prices_assessments_to_show == '') {

					if ($fromdate == '' || $todate == '') {
						//echo $fromdate . ' -- ' . $todate;
						$code = 2001;
						$message = "Both from, end dates are necessary to hit the API";

						return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
					} else {
						$aIds =
							DB::table('tbl_price_static')
							->select(array('relation_id', "f_cnf_fob"))
							//->	where("showOnlyInSteelmint","=", "1")
							->where("continue_or_discontinue", "=", "1")
							->get();

						for ($i = 0; $i < count($aIds); $i++) {
							if ($aIds[$i]['f_cnf_fob'] == 'f')
								$f .=  $aIds[$i]['relation_id'] . ",";
							if ($aIds[$i]['f_cnf_fob'] == 'fob')
								$fob .=  $aIds[$i]['relation_id'] . ",";
							if ($aIds[$i]['f_cnf_fob'] == 'cnf')
								$cnf .=  $aIds[$i]['relation_id'] . ",";
						}

						$f = rtrim($f, ",");
						$cnf = rtrim($cnf, ",");
						$fob = rtrim($fob, ",");

						$filters["itemID"]["f"] = explode(',', $f);
						$filters["itemID"]["cnf"] = explode(',', $cnf);
						$filters["itemID"]["fob"] = explode(',', $fob);

						$prices_assessments_to_show = '';
					}
				}

				if ('' != $prices_assessments_to_show) {
					if ($trade_type) {
						$trade_typeArr = explode(',', $trade_type);
						foreach ($trade_typeArr as $tt) {
							$filters["itemID"][$tt] = explode(',', $prices_assessments_to_show);
						}
						if ($trade_type == 'f')
							$filters["tradeType"] = 'domestic';
					} else {
						$filters["itemID"]["f"] = explode(',', $prices_assessments_to_show);
						$filters["tradeType"] = 'domestic';
					}
				} else {
					if ("qkoeI6XB7YZhxupVE2Oe" == $api_key) {
						$filters["itemID"]["f"] = explode(',', "1067,1234,1004");
						$filters["itemID"]["cnf"] = explode(',', "6,65");
					} elseif ("MGmjoWs61n7qp4k2pXt" == $api_key  || $api_key == '1dP9kOjmxZDt1' || $api_key == 'vByzPZgA5gdMP') {

						//print_r($filters);
					} elseif ("0BKADAbCiQeKomns" == $api_key) {
						$filters["itemID"]["f"] = explode(',', "1387,1401,1108,1047,1234,1228,1229,1418");
						$filters["itemID"]["cnf"] = explode(',', "5327");
					} elseif ("CXkmTOhj7jX3z8Ca56iW" == $api_key) {
						$filters["itemID"]["f"] = explode(',', "1047,1043,1122,1117,1118,1127,1392,1145,1148,1142,1186,1214,1430,1234,1233,1243,1242,1350,1349,1363,1369,1608,1609,1611,1612,1003,1041,1067,1091,1121,1188,1496,1521,1569,1602");
						$filters["itemID"]["fob"] = explode(',', "32,5351");
						$filters["itemID"]["cnf"] = explode(',', "74");
					} elseif ("CXkmTOhj7jX3z8Ca56iW" == $api_key) {
						$filters["itemID"]["f"] = explode(',', "1047,1043,1122,1117,1118,1127,1392,1145,1148,1142,1186,1214,1430,1234,1233,1243,1242,1350,1349,1363,1369,1608,1609,1611,1612,1003,1041,1067,1091,1121,1188,1496,1521,1569,1602");
						$filters["itemID"]["fob"] = explode(',', "32,5351");
						$filters["itemID"]["cnf"] = explode(',', "74");
					} elseif ("QC7uuGXfMy" == $api_key) {
						$filters["itemID"]["f"] = explode(',', "1428,1305,1036,1091,1067,1127,1234,1251,1255");
					} elseif ("k9GNr28K0igD4zu3cFO3" == $api_key) {
						//api added to list steelmint prices in colamint website
						$user_id = 0;
						$cm_app_type = 'CM';
						$resourceType = 'web';
						if ($request->has('resourceType'))
							$resourceType = strtolower($request->input('resourceType'));
						if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
							//$uemail = $request->input('email');//oldPassword
							$token = $request->input('accessToken');
							//$user = new User();
							$auth = new authentication();
							$user_id = $auth->authToken($token, $cm_app_type);
							if (!$user_id)
								return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
						} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

							//$memid = $request->input('memid');
							$memid = htmlentities($request->input('memid'), ENT_QUOTES);

							if (!is_numeric($memid)) {
								return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
							}

							$auth = new authentication();
							$user_id = $auth->authUserId($memid); //for web user
							if (!$user_id)
								return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
						}

						$accessType = 'pre'; //for visitor///
						//echo "User name : ".$user_id;
						if ($user_id) {
							$user = new User($user_id, $cm_app_type);
							///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
							// $isAccessible =  $user->isAccessible($resourceType, $section='Prices');

							$isAccessible =  $user->isAccessible($resourceType, $section = 'Prices', '', '', '', $filters['selected_market']);
							//echo "isAccessible:".$isAccessible;
							if ($isAccessible == -1) {
								$accessType = 'post';
							} else {
								$accessType = 'pre';
							}
						}
						$memid = $user_id;

						$allowed_ass = explode(',', "1401,1091,1096,1067,1503,1127,1407,1406,3016,3015");
						if (isset($filters['itemIdPriceType_f']) && !empty($filters['itemIdPriceType_f'])) {
							$sel_ass = $filters['itemIdPriceType_f'];
							$filters["itemID"]["f"] = array_intersect($sel_ass, $allowed_ass);
						} else
							$filters["itemID"]["f"] = $allowed_ass;

						if ($request->has('currencyName')) {
							$currency = $request->input('currencyName');
						}
					} else {
						if (isset($api_key_dtls[0]['commodityIds'])) {
							$filters["commodityID"] = explode(',', $api_key_dtls[0]['commodityIds']);
						}
					}
				}
				$filters["API_SM_flag"] = 'N';
				if ("0BKADAbCiQeKomns" == $api_key) {
					$filters["API_SM_flag"] = "Y";
				}

				$filters["API_Key"] = '';
				if ($api_key != '') {
					$filters["API_Key"] = $api_key;
				}
				$source = "details";
				$resourceType = "web";
				$offset = 0;
				$pageValue = 1;

				if ($request->has('pageValue') && $request->input('pageValue') != '')
					$pageValue = $request->input('pageValue');
				$offset = ($pageValue - 1) * 20;

				$cntOfRecs = 1;
				$filters['considerTableName'] = $api_key_dtls[0]['considerTableName'];
				if (isset($filters['fromdate']) && $filters['fromdate'] != '') {
					if ($filters['fromdate'] < $api_key_dtls[0]['showDataFrom']) {
						$code = 2001;
						$message = "You are trying to access data beyond authorized date.";

						return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
					} else {
						if ('' != $prices_assessments_to_show) {
							$filters['prices_assessments_to_show'] = $prices_assessments_to_show;
						}
						$cntOfRecs = \ApiQuery::getPricesRowsCnt($filters);
					}
				}



				$result = \ApiQuery::getPricesRows($memid, $source, $resourceType, $type = '', $filters, $accessType, 20, $offset, "SM", $currency);
				return new JsonResponse(array("status" => array("code" => 1001, "message" => "Success"), "data" => $result, "pagesCount" => ceil($cntOfRecs / 20)));
			}
		}
		$resourceType = "app";
		$source = "listing";
		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($request->has('source'))
			$source = strtolower($request->input('source'));

		$filters = array();
		if ($request->has('filters') && !empty($request->input('filters'))) {
			$filters = $request->input('filters');

			///cphrase code
			if ((isset($filters['searchTerms']) && $filters['searchTerms'] != '')) {
				$common = new Common();
				$innerFilterCond = $common->getSearchTermFilterCond($filters['searchTerms']);
				///$innerFilterCond = $this->getSearchTermFilterCond($filters['searchTerms']);

				if (!empty($innerFilterCond) && isset($innerFilterCond['price']) && !empty($innerFilterCond['price'])) {
					$filters['innerFilterCond'] = $innerFilterCond['price'];
					if (!in_array('tbl_exim_master', array_keys($innerFilterCond['price']))) {
						$filters['tradeType'] = 'regional';
					}/* elseif(!in_array('tbl_dom_master', array_keys($innerFilterCond['price']))){
						$fields['filters']['tradeType'] = 'import';
					 } */
					unset($filters['searchTerms']);
				}
			} ////
			if (isset($filters['app_type']) && $filters['app_type'] != '') {
				$this->appType = $filters['app_type'];
			}
		}
		//added condition to handle app api if price_section_type is blank 
		if ($resourceType == 'app') {
			if (strtolower(trim($filters['selected_market'])) == 'future_prices') {
				$filters['price_section_type'] = 'Future_Prices';
				$filters['selected_market'] = '';
			} elseif (empty($filters['price_section_type'])) {
				$filters['price_section_type'] = 'Spot_prices';
			}
		}

		$currency = '';
		if ($request->has('currencyName')) {
			$currency = $request->input('currencyName');
		}

		$offset = 0;
		$pageValue = 1;

		if ($request->has('pageValue') && $request->input('pageValue') != '')
			$pageValue = $request->input('pageValue');

		if (isset($filters['price_section_type'])) {
			if (isset($filters['deviceType']) && $filters['deviceType'] == 'ios')
				$offset = ($pageValue - 1) * 8;
			else
				$offset = ($pageValue - 1) * 11;
		} elseif (isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard') {
			$offset = ($pageValue - 1) * 10;
		} else
			$offset = ($pageValue - 1) * DEFAULT_PRICES_LIMIT;
		$user_id = 0;

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		}

		$accessType = 'pre'; //for visitor///

		if ($user_id) {
			$user = new User($user_id, $this->appType);
			///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
			//$isAccessible =  $user->isAccessible($resourceType, $section='Prices');
			if ($request->has('source') && ($request->input('source') == 'portfolio' || ((strtolower($request->input('source')) == 'commoditywise'  || strtolower($request->input('source')) == 'regionwise') && $resourceType != 'app') || $filters['BlankMarketFlagHandler'] == 'set' || strtolower($filters['price_section_type']) == 'future_prices'))
				$accessType = 'post';
			else {
				$isAccessible = $user->isAccessible($resourceType, $section = 'Prices', '', '', '', $filters['selected_market']);

				if ($isAccessible == -1) {
					$accessType = 'post';
				} else {
					$accessType = 'pre';
				}
			}
		}

		if ($pageValue > 1 || count($filters) > 0) {
			$result = \ApiQuery::getPricesRows($user_id, $source, $resourceType, $type = '', $filters, $accessType, DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);
		} else { /// data from json array file 		
			$result = \ApiQuery::getPricesRows($user_id, $source, $resourceType, $type = 'default', $filters, $accessType, DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);
		}

		$code = 1001;
		$message = "Success";

		if (isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard') {
			$ex = $result;
			$result = array();
			$result = $ex["dataValue"];
			$cntValue = $ex["cntValue"];
		} else {
			$cntValue = 0;
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result, "defaultItemsCount" => 5, "cntValue" => $cntValue, "access" => $accessType));
	}

	private function result_web(&$result)
	{
		$result_with_viewmore = array();
		$vmore = array("parent" => "", "val" => "", "indexer" => false);
		usort($result, array($this, "build_sorted"));
		foreach ($result as $k => $v) {
			$vmore["indexer"] = $vmore["val"] == $v["regionID"] ? true : false;
			if ($vmore["indexer"]) {
				$vmore["parent"] = $vmore["parent"] == "" ? count($result_with_viewmore) - 1 : $vmore["parent"];
				$result_with_viewmore[$vmore["parent"]]["viewmore"][] = $v;
			} else {
				$vmore["parent"] = "";
				$result_with_viewmore[] = $v;
			}

			$vmore["val"] = $v["regionID"];
		}
		return $result_with_viewmore;
	}

	private function build_sorted($a, $b)
	{
		if ($a["regionID"] == $b["regionID"]) {
			return 0;
		}
		return ($a["regionID"] < $b["regionID"]) ? -1 : 1;
	}

	public function getPriceDetails(Request $request)
	{
		$resourceType = "app";
		$filters = array();
		if ($request->has('filters') && !empty($request->input('filters'))) {
			$filters = $request->input('filters');
			if (isset($filters['app_type']) && $filters['app_type'] == 'CM') {
				$this->appType = 'CM';
			}
		}

		//$result = array();	
		$result = null;
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$itemID = 0;
		if ($request->has('itemID') && !empty($request->input('itemID'))) {
			$itemID = $request->input('itemID');
			$filters['itemID'] = $itemID;
			if ($request->has('priceType') && !empty($request->input('priceType'))) {
				$filters['priceType'] = $request->input('priceType');;
			}
		}

		if ($resourceType == 'app' && $request->has('accessToken') && !empty($request->input('accessToken'))) {
			$auth = new authentication();
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && !empty($request->input('memid'))) {
			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$memid = $auth->authUserId($memid); //for web user
		}

		if (isset($filters['app_type']) && $filters['app_type'] == 'CM') {
			$i_id = 5355; //75;
			$priceType = "fob";
		} else {
			$i_id = 1067;
			$priceType = "f";
		}
		if ($request->has('requiredFor') && $request->input('requiredFor') == 'home_pre_login') {
			///billet-> Ex-Raipur 
			//$requiredfor = 'details';
			$itemID = $i_id;
			$filters['itemID'] = $itemID;
			$filters['priceType'] = $priceType;
		}

		if (!$itemID) {
			$code = 2013;
			$message = "Invalid! itemID missing.";

			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		$currency = '';
		if ($request->has('currencyName')) {
			$currency = $request->input('currencyName');
		} elseif ($request->has('currency')) {
			$currency = $request->input('currency');
		}

		$accessType = 'pre';
		if ($memid) {
			///full data///
			//include_once "/home/steelmin/public_html/api/storage/v2019/web/web_prices_details_pre.php"; 
			$user = new User($memid, $this->appType);
			///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
			//$isAccessible =  $user->isAccessible($resourceType, $section='Prices');
			$isAccessible = $user->isAccessible($resourceType, $section = 'Prices', '', '', '', $filters['selected_market']);

			if ($filters['selected_market'] == '') {
				$market_list =
					DB::table('tbl_op_commodity_master')
					->select('f_market')
					->where("id", "=", $itemID)
					->first();
				if (!empty($market_list['f_market']))
					$isAccessible = $user->isAccessibleMarketWise($market_list['f_market']);
			}

			if ($isAccessible == -1) {
				$accessType = 'post';
			}
		}
		if ($request->has('requiredFor') && $request->input('requiredFor') == 'home_pre_login') {
			$accessType = 'post';
			/* echo "<pre>";
			print_r($filters); */
		}

		$resultDetails = \ApiQuery::getPricesRows($memid, $source = 'details', $resourceType, $type = '', $filters, $accessType, 50, $offset = 0, $this->appType, $currency);
		if (count($resultDetails) > 0 && $resourceType != 'app') {
			$result = $resultDetails[0];
		} else {
			$result = $resultDetails;
		}
		$code = 1001;
		$message = "Success";

		$sentiment = array(
			"bullish" => "50.00%",
			"bearish" => "50.00%",
			"description" => "The current bearishness in iron ore (and bulk commodities more broadly) is driven mainly by a weakening demand outlook against a backdrop of ample supply. China, which consumes over half of the world's iron ore, is seeing structurally softer steel demand due to a prolonged property downturn, slower infrastructure growth, and capped steel production for environmental and economic reasons. Steel mill margins are thin, which reduces appetite for spot iron ore and encourages inventory drawdowns rather than fresh buying. At the same time, global supply remains strong, with major producers maintaining high output and new projects gradually adding capacity, reinforcing fears of a surplus. Layered on top of this is a cautious macro outlook."
		);

		$result['rationale'] = $sentiment;

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getPricesGraph(Request $request)
	{
		$result = array();
		$resourceType = "app";

		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));


		$user_id = 0;
		///$user_id = '' ;
		$relation_id = 0;
		$price_type_prefix = 'f';
		$assesment = 'W';
		$currency = '';
		$dateFilter = array();
		$requiredfor = '';
		$_logStartDate = '';
		$filters = array();

		//for selected_market

		if ($request->has('filters') && !empty($request->input('filters'))) {
			$filters = $request->input('filters');
			$selected_market = $filters['selected_market'];
		}
		//added condition to handle app api if price_section_type is blank 
		if ($resourceType == 'app' && strtolower($selected_market) == 'future_prices') {
			$selected_market = '';
		}
		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}


			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($request->has('requiredFor') && $request->input('requiredFor') == 'home_pre_login') {

			///if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
			if ($this->appType == 'CM') {
				/* $i_id = 75;
				$priceType = "fob";
				$assesment = 'W'; */
				$i_id = 5355;
				$priceType = "fob";
				$assesment = 'D';
			} else {
				$i_id = 1067;
				$priceType = "f";
				$assesment = 'D';
			}

			///billet-> Ex-Raipur 
			//$requiredfor = 'home_pre_login';
			$relation_id = $i_id;
			$price_type_prefix = $priceType;

			$dateFilter['fromDate']  = date('Y-m-d', strtotime('-6 months')); //'2015-01-01';
			$dateFilter['toDate']  = date('Y-m-d'); //'2015-12-31';
		}

		include_once($_ENV['COMMON_ROOT_PATH'] . '/mappNew.php');


		if ($request->has('itemID')) {
			$relation_id = $request->input('itemID');
		}

		if (!$relation_id) {
			return new JsonResponse(array("status" => array("code" => 2100, "message" => "Invalid ItemID.")));
		}

		if ($request->has('priceType')) {
			$price_type_prefix = $request->input('priceType');
		}

		if ($request->has('assesment')) {
			$assesment = $request->input('assesment');
		}

		if ($request->has('currencyName')) {
			$currency = $request->input('currencyName');
		}


		if ($request->has('requiredFor')) {
			$requiredfor = $request->input('requiredFor');
		}

		$itemNo = '';
		if ($request->has('itemNo')) {
			$itemNo = $request->input('itemNo');
		}

		if ($request->has('fromDate') && !empty($request->input('fromDate'))) {
			$fromDate = $request->input('fromDate');
			$dateFilter['fromDate'] = $fromDate;
		}

		if ($request->has('toDate') && !empty($request->input('toDate'))) {
			$toDate = $request->input('toDate');
			$dateFilter['toDate'] = $toDate;
		}

		$assessmentType = '';
		if ($request->has('assessmentType') && !empty($request->input('assessmentType'))) {
			$assessmentType = $request->input('assessmentType');
			$dateFilter['assessmentType'] = $assessmentType;
		}

		$convertType = '';
		if ($request->has('convertType') && !empty($request->input('convertType'))) {
			$convertType = $request->input('convertType');
			$dateFilter['convertType'] = $convertType;
		}

		if ($request->has('source') && $request->input('source') == 'newsLetter') {
			$dateFilter['source'] = $request->input('source');
			$dateFilter['fromDate']  = date('Y-m-d', strtotime('-12 months'));
			$dateFilter['toDate']  = date('Y-m-d');
		}

		$code = 1001;
		$message = "Success";
		$f_heading = '';
		if ($requiredfor != 'comparison') {
			$result = array();
			//echo "1:" . $user_id;
			if ($user_id) {
				$user = new User($user_id, $this->appType);
				//$isAccessible =  $user->isAccessible($resourceType, $section='Price Graph');
				$isAccessible =  $user->isAccessible($resourceType, $section = 'Price Graph', '', '', '', $selected_market);
				if ($selected_market == '') {
					$market_list =
						DB::table('tbl_op_commodity_master')
						->select('f_market')
						->where("id", "=", $relation_id)
						->first();
					if (!empty($market_list['f_market']))
						$isAccessible = $user->isAccessibleMarketWise($market_list['f_market']);


					//getting markets of $relation_id
					if ($resourceType == 'app') {
						$get_market_data = $user->getMarketForAPPByItemID($resourceType, $relation_id, 'prices');
						$filters['selected_market'] = $get_market_data;
					}
				}
				//if($isAccessible==-1 )
				if (1) { //send empty data for app when have no access
					////if(116695==$user_id){echo $this->appType; print_r(session()->all());}
					$result = getGraphDataForIdNew($resourceType, $user_id, $relation_id, $price_type_prefix, $assesment, $appType = $this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter, $f_heading, $filters);
				}
			} elseif (1) { //$requiredfor=='home_pre_login' //send empty data for app when have no access
				$result = getGraphDataForIdNew($resourceType, $user_id, $relation_id, $price_type_prefix, $assesment, $appType = $this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter, $f_heading, $filters);
			}
		} else {
			$result = getGraphDataForIdNew($resourceType, $user_id, $relation_id, $price_type_prefix, $assesment, $appType = $this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter, $f_heading, $filters);
		}

		$res = array("status" => array("code" => $code, "message" => $message), "data" => $result);

		$res["currency"] = $currency;

		if ($requiredfor == 'comparison') {
			$res["startDate"] = $_logStartDate;
		}
		$res['isGraphAccessible'] = 'n';
		if ($isAccessible == -1)
			$res['isGraphAccessible'] = 'y';
		return new JsonResponse($res);
	}

	public function getCostIndex(Request $request)
	{
		$result = array();
		include_once "/home/steelmin/public_html/api/storage/v2019/costindex_pre.php";
		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			// $auth = new authentication();
			$token = $request->input('accessToken');
			if (empty($token)) {
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found.";
			} else {
				///full data///
				$code = 1001;
				$message = "Success";
			}
		} else {
			///not loggedin/visitor///

			$code = 1001;
			$message = "Success";
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getPortfolioListItems(Request $request)
	{
		$result = array();
		include_once "/home/steelmin/public_html/api/storage/v2019/portfolio_post.php";
		if ($request->has('accessToken') && $request->input('accessToken') != '') {
			// $auth = new authentication();
			$token = $request->input('accessToken');
			if (empty($token)) {
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found.";
			} else {
				///full data///
				$code = 1001;
				$message = "Success";
			}
		} else {
			///not loggedin/visitor///

			$code = 1001;
			$message = "Success";
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}
	///Comparison/ Display Saved comparison
	public function compare(Request $request)
	{
		/* $result = array();
	   
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
           // $auth = new authentication();
           $token = $request->input('accessToken');
           if(empty($token)){
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found."; 
			}else{
				 //include_once "/home/steelmin/public_html/api/storage/v2019/saved_comparison_display_listing.php";
				 include_once "/home/steelmin/public_html/api/storage/v2019/save_compare.php";
				///full data///
				$code = 1001;
				$message = "Success";
			}
        }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		} */

		$user_id = 0;
		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		}

		$resourceType = "app";
		$filters = array();
		//return $request->all();
		/* if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters'); */
		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'web' || $resourceType == 'app') {
			if ($request->has('item1') && !empty($request->input('item1'))) {
				$item1 = $request->input('item1');
			} else {
				$code = 2013;
				$message = "Invalid! item1 missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item2') && !empty($request->input('item2'))) {
				$item2 = $request->input('item2');
			} else {
				$code = 2013;
				$message = "Invalid! item2 missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}
		} else {
			if ($request->has('item1ID') && !empty($request->input('item1ID'))) {
				$relationID1 = $request->input('item1ID');
			} else {
				$code = 2013;
				$message = "Invalid! item1ID missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item2ID') && !empty($request->input('item2ID'))) {
				$relationID2 = $request->input('item2ID');
			} else {
				$code = 2013;
				$message = "Invalid! item2ID missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item1TradeType') && !empty($request->input('item1TradeType'))) {
				$tradeType1 = $request->input('item1TradeType');
			} else {
				$code = 2013;
				$message = "Invalid! item1 tradeType missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item2TradeType') && !empty($request->input('item2TradeType'))) {
				$tradeType2 = $request->input('item2TradeType');
			} else {
				$code = 2013;
				$message = "Invalid! item2 tradeType missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			$item1['dataType'] = 'price';
			$item2['dataType'] = 'price';

			$item1['relationID'] = $relationID1;
			$item2['relationID'] = $relationID2;

			if (strtolower($tradeType1) == 'domestic')
				$tradeType1 = 'f';
			elseif (strtolower($tradeType1) == 'import')
				$tradeType1 = 'cnf';
			elseif (strtolower($tradeType1) == 'export')
				$tradeType1 = 'fob';

			if (strtolower($tradeType2) == 'domestic')
				$tradeType2 = 'f';
			elseif (strtolower($tradeType2) == 'import')
				$tradeType2 = 'cnf';
			elseif (strtolower($tradeType2) == 'export')
				$tradeType2 = 'fob';

			$item1['tradeType'] = $tradeType1;
			$item2['tradeType'] = $tradeType2;
		}

		if ($request->has('compareName') && !empty($request->input('compareName'))) {
			$compareName = $request->input('compareName');
		}/* else{
			$code = 2013;
			$message = "please enter compare title.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		} */

		if (($resourceType == 'web' || $resourceType == 'app') && !is_array($item1) && !is_array($item2)) {
			$code = 2013;
			$message = "Invalid Input.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		if ($request->has('fromDate') && !empty($request->input('fromDate'))) {
			$fromDate = $request->input('fromDate');
		} else {
			$code = 2013;
			$message = "please enter fromDate.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		if ($request->has('toDate') && !empty($request->input('toDate'))) {
			$toDate = $request->input('toDate');
		} else {
			$code = 2013;
			$message = "please enter to Date.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		$comparisonId = 0;
		if ($request->has('comparisonID') && !empty($request->input('comparisonID'))) {
			$comparisonId = $request->input('comparisonID');
		}

		$assessmentType = '';
		if ($request->has('assessmentType') && !empty($request->input('assessmentType'))) {
			$assessmentType = $request->input('assessmentType');
		}

		include($_ENV['COMMON_ROOT_PATH'] . '/mappNew.php');

		$user_id = 0;
		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}


			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		}

		$relation_id = $id;
		$price_type_prefix = 'f';
		$assessment = 'W';
		$currency = '';

		$dataType1 = isset($item1['dataType']) ? $item1['dataType'] : '';
		$dataType2 = isset($item2['dataType']) ? $item2['dataType'] : '';

		$relation_id1 = isset($item1['relationID']) ? $item1['relationID'] : '';
		$relation_id2 = isset($item2['relationID']) ? $item2['relationID'] : '';

		$price_type_prefix1 = isset($item1['tradeType']) ? $item1['tradeType'] : '';
		$price_type_prefix2 = isset($item2['tradeType']) ? $item2['tradeType'] : '';

		if ($request->has('priceType')) {
			$price_type_prefix = $request->input('priceType');
		}

		if ($request->has('assessment')) {
			$assessment = $request->input('assessment');
		}
		$currencyName = '';
		if ($request->has('currencyName')) {
			$currency = $request->input('currencyName');
			$currencyName = $currency;
		}
		$requiredfor = 'comparison';
		$_logStartDate = '';
		if ($request->has('requiredfor')) {
			$requiredfor = $request->input('requiredfor');
		}

		if ($request->has('requiredFor')) {
			$requiredfor = $request->input('requiredFor');
		}

		$dateFilter = array('fromDate' => $fromDate, 'toDate' => $toDate, 'assessmentType' => $assessmentType);
		$code = 1001;
		$message = "Success";

		$result['item1'] = getGraphDataForIdNew($resourceType, $user_id, $relation_id1, $price_type_prefix1, $assessment, $appType = $this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter, $f_heading);

		$result["currency1"] = $currency;
		$result["item1Title"] = $f_heading;

		$currency = $currencyName;

		$result['item2'] = getGraphDataForIdNew($resourceType, $user_id, $relation_id2, $price_type_prefix2, $assessment, $appType = $this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter, $f_heading);

		$result["currency2"] = $currency;
		$result["item2Title"] = $f_heading;

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	///
	public function compareSave(Request $request)
	{
		$resourceType = "app";
		$filters = array();
		//return $request->all();
		/* if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters'); */
		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'web' || $resourceType == 'app') {
			if ($request->has('item1') && !empty($request->input('item1'))) {
				$item1 = $request->input('item1');
			} else {
				$code = 2013;
				$message = "Invalid! item1 missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item2') && !empty($request->input('item2'))) {
				$item2 = $request->input('item2');
			} else {
				$code = 2013;
				$message = "Invalid! item2 missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}
		} else { //for app

			if ($request->has('item1ID') && !empty($request->input('item1ID'))) {
				$relationID1 = $request->input('item1ID');
			} else {
				$code = 2013;
				$message = "Invalid! item1ID missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item2ID') && !empty($request->input('item2ID'))) {
				$relationID2 = $request->input('item2ID');
			} else {
				$code = 2013;
				$message = "Invalid! item2ID missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item1TradeType') && !empty($request->input('item1TradeType'))) {
				$tradeType1 = $request->input('item1TradeType');
			} else {
				$code = 2013;
				$message = "Invalid! item1 tradeType missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if ($request->has('item2TradeType') && !empty($request->input('item2TradeType'))) {
				$tradeType2 = $request->input('item2TradeType');
			} else {
				$code = 2013;
				$message = "Invalid! item2 tradeType missing.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			}

			if (strtolower($tradeType1) == 'domestic')
				$tradeType1 = 'f';
			elseif (strtolower($tradeType1) == 'import')
				$tradeType1 = 'cnf';
			elseif (strtolower($tradeType1) == 'export')
				$tradeType1 = 'fob';

			if (strtolower($tradeType2) == 'domestic')
				$tradeType2 = 'f';
			elseif (strtolower($tradeType2) == 'import')
				$tradeType2 = 'cnf';
			elseif (strtolower($tradeType2) == 'export')
				$tradeType2 = 'fob';

			$item1['dataType'] = 'price';
			$item2['dataType'] = 'price';

			$item1['relationID'] = $relationID1;
			$item2['relationID'] = $relationID2;

			$item1['tradeType'] = $tradeType1;
			$item2['tradeType'] = $tradeType2;
		}

		if ($request->has('compareName') && !empty($request->input('compareName'))) {
			$compareName = $request->input('compareName');
		} else {
			$code = 2013;
			$message = "please enter compare title.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		if (($resourceType == 'web'  || $resourceType == 'app') && !is_array($item1) && !is_array($item2)) {
			$code = 2013;
			$message = "Invalid Input.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		$tenure = '';
		if ($request->has('tenure') && !empty($request->input('fromDate'))) {
			$tenure = $request->input('tenure');
		}

		if ($request->has('fromDate') && !empty($request->input('fromDate'))) {
			$fromDate = $request->input('fromDate');
		} elseif ($tenure == '') {
			$code = 2013;
			$message = "please enter fromDate.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		if ($request->has('toDate') && !empty($request->input('toDate'))) {
			$toDate = $request->input('toDate');
		} elseif ($tenure == '') {
			$code = 2013;
			$message = "please enter to Date.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		$comparisonId = 0;
		if ($request->has('comparisonID') && !empty($request->input('comparisonID'))) {
			$comparisonId = $request->input('comparisonID');
		}
		$assessmentType = '';
		if ($request->has('assessmentType') && !empty($request->input('assessmentType'))) {
			$assessmentType = $request->input('assessmentType');
		}
		$screenImage = '';
		if ($request->has('screenImage') && !empty($request->input('screenImage'))) {
			$screenImage = $request->input('screenImage');
		}

		if ($request->has('source') && !empty($request->input('source'))) {
			$source = $request->input('source');
		}

		if ($resourceType == 'app' && $request->has('accessToken') && !empty($request->input('accessToken'))) {
			$auth = new authentication();
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && !empty($request->input('memid'))) {
			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$memid = $auth->authUserId($memid); //for web user
		}

		if ($memid) {
			$screenImage = "";
			$screenImage = date('YmdHi') . '_' . $memid . ".png";
			if ($request->has('screenImage')) {
				$str = str_replace('\\', '', $request->input('screenImage'));
				$str = str_replace(' ', '+', $str);
				$str = base64_decode($str);

				$screenImage = date('YmdHi') . '_' . $memid . ".png";
				file_put_contents("/home/steelmin/public_html/api/public/uploads/compare/" . $screenImage, $str);
			}

			$uData = array(
				"updatedOn" => $GLOBALS['currDateTime'],
				"memid" => $memid,
				"compareName" => $compareName,
				"screenImage" => $screenImage,
				"dataType1" => $item1['dataType'],
				"dataType2" => $item2['dataType'],
				"tradeType1" => isset($item1['tradeType']) ? $item1['tradeType'] : '',
				"tradeType2" => isset($item2['tradeType']) ? $item2['tradeType'] : '',
				"commodityID1" => isset($item1['commodityID']) ? $item1['commodityID'] : '',
				"commodityID2" => isset($item2['commodityID']) ? $item2['commodityID'] : '',
				"regionID1" => isset($item1['regionID']) ? $item1['regionID'] : '',
				"regionID2" => isset($item2['regionID']) ? $item2['regionID'] : '',
				"relationID1" => isset($item1['relationID']) ? $item1['relationID'] : '',
				"relationID2" => isset($item2['relationID']) ? $item2['relationID'] : '',

				"columnNameOfRegion1" => isset($item1['columnNameOfRegion']) ? $item1['columnNameOfRegion'] : '',
				"columnNameOfCommodity1" => isset($item1['columnNameOfCommodity']) ? $item1['columnNameOfCommodity'] : '',
				"2ndLevel1" => isset($item1['childHeaderName']) ? $item1['childHeaderName'] : '',
				"2ndLevel1Value" => isset($item1['childHeaderValue']) ? $item1['childHeaderValue'] : '',
				"2ndLevel1headerColumn" => isset($item1['childHeaderColumn']) ? $item1['childHeaderColumn'] : '',

				"columnNameOfRegion2" => isset($item2['columnNameOfRegion']) ? $item2['columnNameOfRegion'] : '',
				"columnNameOfCommodity2" => isset($item2['columnNameOfCommodity']) ? $item2['columnNameOfCommodity'] : '',
				"2ndLevel2" => isset($item2['childHeaderName']) ? $item2['childHeaderName'] : '',
				"2ndLevel2Value" => isset($item2['childHeaderValue']) ? $item2['childHeaderValue'] : '',
				"2ndLevel2headerColumn" => isset($item2['childHeaderColumn']) ? $item2['childHeaderColumn'] : '',

				"tenure" => $tenure,
				"fromDate" => $fromDate,
				"toDate" => $toDate,
				"assessmentType" => $assessmentType,
				"resourceType" => $resourceType
			);

			//else insert new device details
			if ($comparisonId <= 0) { //insert
				$uData["createdOn"] = $GLOBALS['currDateTime'];
				$comparisonId = DB::table('tbl_compare')->insertGetId($uData);
			} else {

				DB::table('tbl_compare')
					->where("id", "=", $comparisonId)
					->update($uData);
			}

			$code = 1001;
			$message = "Successfully Saved";
			$result['comparisonId'] = $comparisonId;
		} else {
			$code = 2100;
			$message = "Invalid User or User not found.";
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	//Compare - Mapping data
	public function compareFilterList(Request $request)
	{
		$result = array();
		/* $section = $request->input('section');
		$tradeType = $request->input('tradeType');
		$regionID = $request->input('regionID'); */

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}


			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		}

		$filters = array();
		if ($request->has('filters') && !empty($request->input('filters'))) {
			$filters = $request->input('filters');
			if (isset($filters['app_type']) && $filters['app_type'] != '')
				$this->appType = $filters['app_type'];
		}


		$deviceType = "";
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		if ($user_id) {
			/* $user = new User($user_id, $this->appType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Price Graph');
			
			if(!empty(Session::get('sectionFromDate'))){			
				$sectionFromDate = Session::get('sectionFromDate');
				$sectionTodate = Session::get('sectionTodate');			
			}
			 */
			$result = \ApiQuery::getPricesFilterNew($user_id, $this->appType, $deviceType);
			$code = 1001;
			$message = "Success";
		} else {
			$code = 2100;
			$message = "Invalid User or User not found.";
		}

		/* if($regionID==''){
			$code = 9999;
			$message = "Please select region."; 
		}elseif($tradeType==''){
			$code = 9999;
			$message = "Please select tradeType."; 
		}else 
		{
			$result = \ApiQuery::getPricesFilter($section, $tradeType, $regionID, $this->appType);
			$result = \ApiQuery::getPricesFilterNew($section, $this->appType);
			$result = \ApiQuery::getPricesFilterNew();
			$code = 1001;
			$message = "Success";
		}*/
		/* if($resourceType=='web'){
			include_once "/home/steelmin/public_html/api/storage/v2019/web/compare_mapping_post.php";
		}else{
			include_once "/home/steelmin/public_html/api/storage/v2019/compare_mapping_post.php";
		} */
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getDateRangeFilter(Request $request)
	{
		$result = array();

		if ($request->has('section') && !empty($request->input('section'))) {
			$section = $request->input('section');
		} else {
			$code = 2013;
			$message = "Section type missing.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		if ($request->has('itemID') && !empty($request->input('itemID'))) {
			$itemID = $request->input('itemID');
		} else {
			$code = 2013;
			$message = "ItemIds missing.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}
		//print_r($itemID);
		///return $request->input('itemID');

		include_once($_ENV['COMMON_ROOT_PATH'] . '/helper.php');
		$condition = "relation_id IN (" . implode(',', $itemID) . ")";
		$dateRange = getDateRange($section, $condition);
		$result['dateRange'] = $dateRange;

		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	//Saved comparison listing
	public function getCompareSavedList(Request $request)
	{
		$resourceType = "app";
		$filters = array();
		//return $request->all();

		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'app' && $request->has('accessToken') && !empty($request->input('accessToken'))) {
			$auth = new authentication();
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token, $this->appType);
		} elseif ($resourceType == 'web' && $request->has('memid') && !empty($request->input('memid'))) {
			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$memid = $auth->authUserId($memid); //for web user
		}
		$itemID = 0;
		if ($request->has('itemID') && !empty($request->input('itemID'))) {
			$itemID = $request->input('itemID');
		}

		if ($memid) {
			$code = 1001;
			$message = "Success";
			$result = \ApiQuery::getPricesCompareSavedRows($resourceType, $memid, $itemID);
		} else {
			$code = 2013;
			$message = "User not found.";
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function getHistoricalData(Request $request)
	{
		$resourceType = "APP";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		$code = 1001;
		$message = "Success";
		if ($request->has('memid') && $request->input('memid') != '') {

			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}


			include_once "/home/steelmin/public_html/api/storage/v2019/web/history_prices_post.php";
		} else {
			include_once "/home/steelmin/public_html/api/storage/v2019/web/history_prices_pre.php";
		}
		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result, "defaultItemsCount" => 5));
	}

	public function compareUpdate(Request $request)
	{
		$resourceType = "app";
		$filters = array();
		$result = array();
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));


		if ($request->has('comparisonID') && !empty($request->input('comparisonID'))) {
			$comparisonID = $request->input('comparisonID');
		} else {
			$code = 2013;
			$message = "Comparison ID missing.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		if ($request->has('compareName') && !empty($request->input('compareName'))) {
			$compareName = $request->input('compareName');
		} else {
			$code = 2013;
			$message = "please enter compare title.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		$user_id = 0;
		if ($request->has('memid') && !empty($request->input('memid'))) {
			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
		} else {
			$code = 2013;
			$message = "memid missing.";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}

		if ($user_id) {

			$uData = array(
				"updatedOn" => $GLOBALS['currDateTime'],
				///"memid"=>$memid,
				"compareName" => $compareName
			);

			DB::table('tbl_compare')
				->where("id", "=", $comparisonID)
				->update($uData);

			$code = 1001;
			$message = "Successfully Updated";
			$result['comparisonID'] = $comparisonID;
		} else {
			$code = 2100;
			$message = "Invalid User or User not found.";
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $result));
	}

	public function bySectionType(Request $request)
	{

		$result = array();
		$resourceType = 'web';
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$deviceType = '';
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));

		$user_id = 0;
		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		}

		$accessType = 'pre'; //for visitor///
		$market_arr =
			array(
				"ferrous",
				"non-ferrous",
				"coal",
				"scrap-recycling",
				"agriculture"
			);
		/* $market_arr_futures = 
            array(
               'future_prices=ferrous','future_prices=non-ferrous','future_prices=coal','future_prices=scrap-recycling'
            );*/
		$price_section_type = '';
		$selected_market = '';
		$file_postfix = '';
		if ($request->has('price_section_type') && $request->input('price_section_type') != '') {
			$price_section_type = strtolower($request->input('price_section_type'));
			/*if(in_array($request->input('price_section_type'),$market_arr_futures)){
                $p_arr =explode("=",$price_section_type);
                $price_section_type = $p_arr[0];
                $selected_market = $p_arr[1];
                $file_postfix = "_".$selected_market;
            }*/
			if (in_array($request->input('price_section_type'), $market_arr)) {
				$price_section_type = strtolower("spot_prices");
				$selected_market = strtolower($request->input('price_section_type'));
				$file_postfix = "_" . $selected_market;
			}
		} else
			return new JsonResponse(array("status" => array("code" => 2100, "message" => "Invalid Price Section.")));


		if ($user_id) {
			$user = new User($user_id, $this->appType);
			///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
			//$isAccessible =  $user->isAccessible($resourceType, $section='Prices');
			$isAccessible =  $user->isAccessible($resourceType, $section = 'Prices', '', '', '', $selected_market);

			if ($isAccessible == -1) {
				$accessType = 'post';
			} elseif (!empty(session('marketsIncludes')) && $price_section_type == 'future_prices') {
				$accessType = 'post';
			} else {
				$accessType = 'pre';
			}
		}
		/*$price_section_type='';
		if($request->has('price_section_type') && $request->input('price_section_type')!='')
			$price_section_type = strtolower($request->input('price_section_type'));
		else
			return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Invalid Price Section.")));
        */
		if ($this->appType == 'CM')
			$filename = "https://www.steelmint.com/v2019_bm/Json/price_section_type/CM/" . $accessType . "_" . $deviceType . "_" . $price_section_type . $file_postfix . ".json";
		else
			$filename = "https://www.steelmint.com/v2019_bm/Json/price_section_type/" . $accessType . "_" . $deviceType . "_" . $price_section_type . $file_postfix . ".json";

		if ($accessType == 'post') {
			$result = file_get_contents($filename);
			$p_array = json_decode($result, true);
			$common = new Common();
			$c = $common->getBookmarked($user_id, $p_array, true);
			$result = json_encode($c);
			return $result;
		} else {
			return file_get_contents($filename);
		}
	}

	//price participant tab data
	public function getPriceParticipantTabData(Request $request)
	{
		$result = $data = array();

		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		$itemID = "";
		if ($request->has('itemID'))
			$itemID = $request->input('itemID');
		$fDate = '';
		if ($request->has('fDate'))
			$fDate = $request->input('fDate');

		$user_id = 0;
		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {

			//$memid = $request->input('memid');
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);

			if (!is_numeric($memid)) {
				return new JsonResponse(array("status" => array("code" => 2001, "message" => "Improper input values")));
			}

			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id)
				return new JsonResponse(array("status" => array("code" => 2100, "message" => "Unauthorized action.")));
		}

		if ($itemID && $user_id) {
			$result = \ApiQuery::get_data_collection_participants($itemID, $fDate);
			if ($result['status'] == 1001) {
				$code = 1001;
				$message = "Success";
				$data = $result['data'];
			} else {
				$code = $result['status'];
				$message = $result['message'];
			}
		} else {
			$code = 2100;
			$message = "Invalid User or User not found/Invalid input.";
		}

		return new JsonResponse(array("status" => array("code" => $code, "message" => $message), "data" => $data));
	}
	//replaced the old link as session variable not supported cross origin 
	//https://www.steelmint.com/ajax_calls.php?getTmtAll=TMT&supplier=SECONDARY&fdate=2024-09-20
	//Commented by NXS on 30th April 2026
	// public function getTmtAllSizes(Request $request){    
	//     $resourceType = "app";			
	// 	if($request->has('resourceType'))
	// 		$resourceType = strtolower($request->input('resourceType'));

	//     if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {			
	// 		$token = $request->input('accessToken');
	// 		$user = new User();
	// 		$auth = new authentication();
	// 		$user_id = $auth->authToken($token,$this->appType);
	// 		if(!$user_id){
	// 			echo "Unauthorized action.";
	// 			die;
	//         }
	// 	}elseif ($resourceType=='web' && $request->has('memid') && $request->input('memid')!=''){
	//         $memid = htmlentities($request->input('memid'), ENT_QUOTES);
	//         if( !is_numeric($memid) ){
	//             return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
	//         }
	// 		$auth = new authentication();
	// 		$user_id = $auth->authUserId($memid);//for web user
	// 		if(!$user_id){
	// 			echo "Unauthorized action.";
	// 			die;
	//         }
	// 	}
	// 	$supplier='';$filters=array();$getTmtAll='';$fdate='';
	// 	if($request->has('filters') && !empty($request->input('filters')))
	//         $filters = $request->input('filters');		
	//     if($request->has('getTmtAll'))
	//         $getTmtAll = $request->input('getTmtAll');
	// 	if($request->has('supplier'))
	//         $supplier = $request->input('supplier');
	// 	if($request->has('fdate'))
	//         $fdate = $request->input('fdate');
	//     $app_type= $this->appType;
	//     if(!empty($getTmtAll) && !empty($supplier) && !empty($fdate)){          
	//         $result = \ApiQuery::getPricesTmtAll($user_id,$resourceType,$app_type,$getTmtAll, $supplier, $fdate,$filters);	
	//         echo $result;
	//     }
	// }
	public function getTmtAllSizes(Request $request)
	{
		$resourceType = "app";
		$user_id = 0;
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if ($resourceType == 'app' && $request->has('accessToken') && $request->input('accessToken') != '') {
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token, $this->appType);
			if (!$user_id) {
				return new JsonResponse(array("code" => 401, "status" => false, "message" => "Unauthorized action."));
			}
		} elseif ($resourceType == 'web' && $request->has('memid') && $request->input('memid') != '') {
			$memid = htmlentities($request->input('memid'), ENT_QUOTES);
			if (!is_numeric($memid)) {
				return new JsonResponse(array("code" => 400, "status" => false, "message" => "Improper input values"));
			}
			$auth = new authentication();
			$user_id = $auth->authUserId($memid); //for web user
			if (!$user_id) {
				return new JsonResponse(array("code" => 401, "status" => false, "message" => "Unauthorized action."));
			}
		} else {
			return new JsonResponse(array("code" => 400, "status" => false, "message" => "Missing auth input."));
		}
		$supplier = '';
		$filters = array();
		$getTmtAll = '';
		$fdate = '';
		if ($request->has('filters') && !empty($request->input('filters')))
			$filters = $request->input('filters');
		if ($request->has('getTmtAll'))
			$getTmtAll = $request->input('getTmtAll');
		if ($request->has('supplier'))
			$supplier = $request->input('supplier');
		if ($request->has('fdate'))
			$fdate = $request->input('fdate');
		$app_type = $this->appType;
		if (!empty($getTmtAll) && !empty($supplier) && !empty($fdate)) {
			$result = \ApiQuery::getPricesTmtAll($user_id, $resourceType, $app_type, $getTmtAll, $supplier, $fdate, $filters);
			return new JsonResponse(array("code" => 200, "status" => true, "data" => $result));
		}
		return new JsonResponse(array("code" => 400, "status" => false, "message" => "Required input missing: getTmtAll, supplier, fdate"));
	}

	public function getLivePricesAPI(Request $request)
	{
		//insert - request log starts
		$vendorData = array();

		$vendorData['endpoint'] = $request->fullUrl(); // Get the current endpoint
		$vendorData['request_json'] = json_encode($request->all());
		$vendorData['request_at'] = date("Y-m-d H:i:s");
		// Capture the 'api_key' input if it exists
		if ($request->has('api_key')) {
			$vendorData['api_key'] = $request->input('api_key');
		}
		// Capture the 'commodityID' input if it exists
		if ($request->has('commodityID')) {
			$vendorData['commodityID'] = $request->input('commodityID');
		}
		// Capture the 'regionID' input if it exists
		if ($request->has('regionID')) {
			$vendorData['regionID'] = $request->input('regionID');
		}
		// Insert the data into the 'tbl_vendor_api_history' table and get the inserted ID
		$comparisonId = DB::table('tbl_vendor_api_history')->insertGetId($vendorData);

		if ($request->has('api_key')) {
			$commodityIDSubscribedTo = '';
			$prices_assessments_to_show = '';
			$commodityIDFilter = '';
			$regionIDFilter = '';
			$appType = 'SM';

			$api_key = $request->input('api_key');
			$api_key_dtls =
				DB::table('tbl_customized_apis')
				->select(array('considerTableName', 'enddate', 'prices_assessments_to_show', 'showDataFrom', 'consider_all_assessments', 'commodityIds', 'f_market'))
				->where("api_key", "=", $api_key)
				->where("enddate", ">=", date("Y-m-d"))
				->where("startdate", "<=", date("Y-m-d"))
				->get();
			//dd(DB::getQueryLog());
			//print_r($api_key_dtls);
			if (count($api_key_dtls) == 0) {
				$code = 2001;
				$message = "The API key is invalid or it has expired.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			} else {
				if ($request->has('appType') && !empty($request->input('appType')))
					$appType = $request->input('appType');

				//$considerTableName = '';
				$consider_all_assessments = $api_key_dtls[0]['consider_all_assessments'];

				if (isset($api_key_dtls[0]['commodityIds'])) {
					$commodityIDSubscribedTo = $api_key_dtls[0]['commodityIds'];
				}

				if (isset($api_key_dtls[0]['prices_assessments_to_show'])) {
					$prices_assessments_to_show = $api_key_dtls[0]['prices_assessments_to_show'];
				}

				if (isset($api_key_dtls[0]['f_market'])) {
					$f_market = $api_key_dtls[0]['f_market'];
				}

				if ($request->has('commodityID') && !empty($request->input('commodityID')))
					$commodityIDFilter = $request->input('commodityID');

				if ($request->has('regionID') && !empty($request->input('regionID')))
					$regionIDFilter = $request->input('regionID');
				$result = \ApiQuery::getLivePriceRowsAPI($commodityIDSubscribedTo, $prices_assessments_to_show, $commodityIDFilter, $regionIDFilter, $consider_all_assessments, $appType, $api_key, $f_market);
				return new JsonResponse(array("status" => array("code" => 1001, "message" => "Success"), "data" => $result));
			}
		} else {
			$code = 2001;
			$message = "API Key is mandatory in request";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}
	}

	//Created function for sharing prices for news media plates
	//YKV 05th August 2025
	public function getBigMintPricesPlate(Request $request)
	{
		//insert - request log starts
		$vendorData = array();

		$vendorData['endpoint'] = $request->fullUrl(); // Get the current endpoint
		$vendorData['request_json'] = json_encode($request->all());
		$vendorData['request_at'] = date("Y-m-d H:i:s");
		// Capture the 'api_key' input if it exists
		if ($request->has('api_key')) {
			$vendorData['api_key'] = $request->input('api_key');
		}
		// Capture the 'commodityID' input if it exists
		if ($request->has('commodityID')) {
			$vendorData['commodityID'] = $request->input('commodityID');
		}
		// Capture the 'regionID' input if it exists
		if ($request->has('regionID')) {
			$vendorData['regionID'] = $request->input('regionID');
		}
		// Insert the data into the 'tbl_vendor_api_history' table and get the inserted ID
		$comparisonId = DB::table('tbl_vendor_api_history')->insertGetId($vendorData);

		if ($request->has('api_key')) {
			$commodityIDSubscribedTo = '';
			$prices_assessments_to_show = '';
			$commodityIDFilter = '';
			$regionIDFilter = '';
			$appType = 'SM';

			$api_key = $request->input('api_key');
			$api_key_dtls =
				DB::table('tbl_customized_apis')
				->select(array('considerTableName', 'enddate', 'prices_assessments_to_show', 'showDataFrom', 'consider_all_assessments', 'commodityIds'))
				->where("api_key", "=", $api_key)
				->where("enddate", ">=", date("Y-m-d"))
				->where("startdate", "<=", date("Y-m-d"))
				->get();
			//dd(DB::getQueryLog());
			//print_r($api_key_dtls);
			if (count($api_key_dtls) == 0) {
				$code = 2001;
				$message = "The API key is invalid or it has expired.";
				return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
			} else {
				if ($request->has('appType') && !empty($request->input('appType')))
					$appType = $request->input('appType');

				//$considerTableName = '';
				$consider_all_assessments = $api_key_dtls[0]['consider_all_assessments'];

				if (isset($api_key_dtls[0]['commodityIds'])) {
					$commodityIDSubscribedTo = $api_key_dtls[0]['commodityIds'];
				}

				if (isset($api_key_dtls[0]['prices_assessments_to_show'])) {
					$prices_assessments_to_show = $api_key_dtls[0]['prices_assessments_to_show'];
				}

				if ($request->has('commodityID') && !empty($request->input('commodityID')))
					$commodityIDFilter = $request->input('commodityID');

				if ($request->has('regionID') && !empty($request->input('regionID')))
					$regionIDFilter = $request->input('regionID');
				$result = \ApiQuery::getPricesForPlate($prices_assessments_to_show, $consider_all_assessments, $api_key);
				return new JsonResponse(array("status" => array("code" => 1001, "message" => "Success"), "data" => $result));
			}
		} else {
			$code = 2001;
			$message = "API Key is mandatory in request";
			return new JsonResponse(array("status" => array("code" => $code, "message" => $message)));
		}
	}
}
