<?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 Session;
class InsightsController extends Controller
{ 
    public $appType = 'SM' ;
	public function __construct(Request $request) {
        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;			
        }
		elseif($request->has('filters')){
			 $filter = $request->input('filters');
			 if(!empty($filter['app_type'])){
					$this->appType = 'CM';
			 }
		} elseif($request->has('app_type') && $request->input('app_type') == true) {
            $this->appType = $request->input('app_type');		
        }
    }
	
	
	public function getInsights(Request $request)
    {
		
		//\ApiQuery::create_json_for_region();
		$resourceType = "app";
		$source = "listing";
		$result = array();	
		$shareText = "Download SteelMint mobile application: https://www.steelmint.com/apps.php";
		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');
		    
			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
			   
				$this->appType = "CM";//if coalmint then show only colamint related tenders
				$shareText = "Download CoalMint mobile application: https://www.coalmint.com/apps.php";
			}			
			///cphrase code
			if( isset($filters['searchTerms'])){
				$common = new Common();
				$innerFilterCond = $common->getSearchTermFilterCond($filters['searchTerms'], 'insight');
				
				if(!empty($innerFilterCond)){
					unset($filters['searchTerms']);
			    }
			    if(isset($innerFilterCond['commodity']) && !empty($innerFilterCond['commodity']) && ($innerFilterCond['commodity']!='all')){
					$filters['commodityID'] = array($innerFilterCond['commodity']);
				}
				if(isset($innerFilterCond['location']) && !empty($innerFilterCond['location']) && ($innerFilterCond['location']!='all')){
					$filters['regionID'] = array($innerFilterCond['location']);
				}				
			}///
		}
		
		$offset=0;
		$pageValue=1;
		
		if ($request->has('pageValue') && $request->input('pageValue')!=''){
			$pageValue = $request->input('pageValue');	
			if($pageValue>1 && (strtolower($source)=='commoditywise' || strtolower($source)=='regionwise' || strtolower($source)=='regioncommoditywise'))
				$source = "listing";
				
		}
		if($resourceType=='web'){
			$code = 1001;				
			$message = "Success";
			
			if( isset($filters['association_pmai']) && $filters['association_pmai'] == 'Y' )
				if( isset($filters['widget_name']) && $filters['widget_name'] == 'coalshastra' )
					$offset = ($pageValue-1)* 4;
				else
					$offset = ($pageValue-1)* 5;
			else	
				$offset = ($pageValue-1)* DEFAULT_NEWS_LIMIT;
			
			if ($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")));
                }
				
				//$memid = _encrypt_decrypt($action='decrypt', $memid);
				$auth = new authentication();
				$user_id = $auth->authUserId($memid);//for web user
				//print_r($filters);
				if ($user_id) {
					//run query here
					/* $user = new User($user_id, $this->appType);
					$isAccessible = $user->getTakenServicesByUser($item='Insights', $at_place='mobileapp', $tenderDateToCompare=date('Y-m-d'));
					if ($isAccessible==-1) {
						$accessType = 'post';
					}else{
						$accessType = 'pre';
					} */

					if($pageValue>1 || count($filters)>0){			
						$result = \ApiQuery::getInsightsRows($user_id, $source, $resourceType, $type='', $filters,'post',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
						/* $sql = DB::table('tbl_news_post')->offset($offset)->limit(DEFAULT_LIMIT); 
						$result = $sql->get(); */
					}else {/// data from json array file 
					
						$result = \ApiQuery::getInsightsRows($user_id, $source, $resourceType, $type='default', $filters,'post',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
						////$sql = DB::table('tbl_news_post')->limit(DEFAULT_NEWS_LIMIT); 
						///include_once "/home/steelmin/public_html/api/storage/v2019/json/web/insight/listing_post.php";
					}
				}else{
					$code = 2100;
					$message = "Unauthorized action.";
				}
			}else{/// pre data from json array file 
				////$sql = DB::table('tbl_news_post')->limit(5); //pre
				if($pageValue>1 || count($filters)>0){	//added on 16/12/19
					$result = \ApiQuery::getInsightsRows($memid=0, $source, $resourceType, $type='', $filters,'pre',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
				}else{
					$result = \ApiQuery::getInsightsRows($memid=0, $source, $resourceType, $type='default', $filters,'pre',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
				//include_once "/home/steelmin/public_html/api/storage/v2019/json/web/insight/listing_pre.php";
				}
			}
		}else{
			///include('/home/steelmin/public_html/api/storage/v2019/insight_pre.php');
			$offset = ($pageValue-1)* DEFAULT_NEWS_LIMIT;
			if ($request->has('accessToken') && $request->input('accessToken')!='') {
			   // $auth = new authentication();
					$auth = new authentication();	
					$token = $request->input('accessToken');
					$memid = $auth->authToken($token,$this->appType);	
					
					//$pageValue = $request->input('pageValue');					
					
					
					if ($memid) {
						if($pageValue>1 || count($filters)>0){			
							$result = \ApiQuery::getInsightsRows($memid, $source, $resourceType, $type='', $filters,'post',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
						}else {/// data from json array file 
							$result = \ApiQuery::getInsightsRows($memid, $source, $resourceType, $type='default', $filters,'post',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
							////$sql = DB::table('intel')->limit(DEFAULT_NEWS_LIMIT); 
							//include_once "/home/steelmin/public_html/api/storage/v2019/json/app/insight/post.php";
						}
						///include('/home/steelmin/public_html/api/storage/v2019/insight_post.php');
						$code = 1001;
						$message = "Success";
					}else{
						$code = 2100;
						$message = "Unauthorized action.";
					}
			}else{
				///not loggedin/visitor/////pre
				if($pageValue>1 || count($filters)>0){	//added on 16/12/19
					$result = \ApiQuery::getInsightsRows($memid=0, $source, $resourceType, $type='', $filters,'pre',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
				}else{
					$result = \ApiQuery::getInsightsRows($memid=0, $source, $resourceType, $type='default', $filters,'pre',DEFAULT_NEWS_LIMIT, $offset, $this->appType);
				}
					//include_once "/home/steelmin/public_html/api/storage/v2019/json/app/insight/pre.php";
				$code = 1001;
				$message = "Success";
			}
		}
		$accessType = 'pre';
		$chkVisitHistoryCount = 0;
		if($memid){
			$user = new User($memid, $this->appType);
			//$isAccessible =  $user->isAccessible($resourceType);//, $section='Insights'
			$isAccessible = $user->isAccessible($resourceType,'Prices','','','',$filters['selected_market']);
			if($filters['debug']=="1"){
                
                    print_r(session()->all());
                    echo "----->".$isAccessible;
                }
			if ($isAccessible==-1) {
				$accessType = 'post';
				
				//echo Session::get('userService'); 
				if(
                    Session::has($filters['selected_market']) && 
                    (Session::get($filters['selected_market'])['userService'] == 'Corporate Standard' || 
                     Session::get($filters['selected_market'])['userService'] == 'Standard' || 
                     Session::get($filters['selected_market'])['userService'] == 'Free Trial'
                     )
                ){
					$chkVisitHistoryCount = $this->appType=='CM'?1:10;
					
				}elseif(Session::has($filters['selected_market']) && (Session::get($filters['selected_market'])['userService'] == 'Price Only' )){//
					$chkVisitHistoryCount = $this->appType=='CM'?1:2;					
				}
								
			}else{
				$accessType = 'pre';
				$chkVisitHistoryCount = $this->appType=='CM'?1:2;
				
			} 
		}	
		if($memid==78616){
			//print_r(session()->all());
			//echo $accessType ."--".$chkVisitHistoryCount;
		}
		//$data1 = session()->all();
		///not loggedin/visitor///
		$visitorID = 0;$preCount=0;
		if((($request->has('visitorID') || $memid>0) && $accessType=='pre') || ($accessType == 'post' && $chkVisitHistoryCount > 0)) {
			if($request->has('visitorID')){
				$visitorID = $request->input('visitorID');		
				$chkVisitHistoryCount = $this->appType=='CM'?1:2;
			}				
			
			$common = new Common();
			$preCount = $common->getVisitorCountPerWeek($section='insight', $resourceType, $this->appType, $memid, $visitorID, $visitedItem='');
			
			if(count($result)>0){
			//if(1){
				$result[0]["totalAlreadyViewed"] = $preCount; 
				$result[0]["totalAllowedToView"] = $chkVisitHistoryCount;
			}
			
    	   //if($resourceType == "web" && $source == 'mapview') 
    	//	  $result = $this->result_web($result);
		  //'tt'=>$data1
			// return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result,"shareText" => $shareText));

			$response = array("status"=>array("code" => $code, "message" => $message), "data"=> $result,"shareText" => $shareText);
			if ($pageValue == 1 && strtolower($source) == 'listing') {
				$response = array_merge($response, $this->getStaticInsightsFeedSections());
			}
			return new JsonResponse($response);
		}
		
		////$filters['visitor_history_id'] = $visitorID;

	  // if($resourceType == "web" && $source == 'mapview') 
		//  $result = $this->result_web($result);

       //$data1 = session()->all();																										
	   $response = array("status"=>array("code" => $code, "message" => $message), "data"=> $result,"shareText" => $shareText);
	   if ($pageValue == 1 && strtolower($source) == 'listing') {
		   $response = array_merge($response, $this->getStaticInsightsFeedSections());
	   }
	   return new JsonResponse($response);
	}

	/**
	 * Static home-feed rows for Flash news, Analyst corner, and Editor's pick (placeholder until backed by data).
	 */
	protected function getStaticInsightsFeedSections()
	{
		// Base path or CDN for images; update as needed.
		$imageBaseUrl = env('INSIGHT_IMAGE_PREFIX', 'https://cdn.metal-site.com/insights/');

		return array(
			'flashNews' => array(
				array(
					'category'     => 'Intel',
					'subCategory'  => 'Iron Ore',
					'title'        => "Global iron ore exports show divergent trends in CY'25; India...",
					'timestamp'    => '29 Jan 15:51 IST',
					'readingTime'  => '3 min read',
					'icon'         => 'layered-stack',
					'themeColor'   => '#3b6fc9',
					'imageURL'     => $imageBaseUrl . 'flashnews1.jpg',
				),
				array(
					'category'     => 'Insights',
					'subCategory'  => 'Coal',
					'title'        => 'India: Over 140,000 t of iron ore booked in Odisha auction',
					'timestamp'    => '29 Jan 14:30 IST',
					'readingTime'  => '2 min read',
					'icon'         => 'lightning',
					'themeColor'   => '#4a5568',
					'imageURL'     => $imageBaseUrl . 'flashnews2.jpg',
				),
				array(
					'category'     => 'Intel',
					'subCategory'  => 'Steel',
					'title'        => 'China steel output cuts deepen amid prolonged property slump in...',
					'timestamp'    => '29 Jan 12:15 IST',
					'readingTime'  => '4 min read',
					'icon'         => 'briefcase',
					'themeColor'   => '#c67d3e',
					'imageURL'     => $imageBaseUrl . 'flashnews3.jpg',
				),
				array(
					'category'     => 'Insights',
					'subCategory'  => 'Coal',
					'title'        => 'Coking coal prices soften as Australian supply normalises post...',
					'timestamp'    => '29 Jan 10:00 IST',
					'readingTime'  => '3 min read',
					'icon'         => 'circle-cross',
					'themeColor'   => '#2f855a',
					'imageURL'     => $imageBaseUrl . 'flashnews4.jpg',
				),
			),
			'analystCorner' => array(
				array(
					'category'     => 'Analysis',
					'subCategory'  => 'Iron Ore',
					'title'        => 'Iron ore prices likely to stay range-bound in Q1 FY27 amid weak...',
					'timestamp'    => '29 Jan 16:00 IST',
					'readingTime'  => '4 min read',
					'icon'         => 'line-chart',
					'themeColor'   => '#3182ce',
					'imageURL'     => $imageBaseUrl . 'analyst1.jpg',
				),
				array(
					'category'     => 'Analysis',
					'subCategory'  => 'Steel',
					'title'        => 'Steel exports from India may rise 15% in FY26 on global demand...',
					'timestamp'    => '28 Jan 10:30 IST',
					'readingTime'  => '5 min read',
					'icon'         => 'rectangle',
					'themeColor'   => '#718096',
					'imageURL'     => $imageBaseUrl . 'analyst2.jpg',
				),
				array(
					'category'     => 'Analysis',
					'subCategory'  => 'Copper',
					'title'        => 'Copper supply deficit to widen in 2026; prices may test $10,500/t',
					'timestamp'    => '27 Jan 14:15 IST',
					'readingTime'  => '3 min read',
					'icon'         => 'circle',
					'themeColor'   => '#dd6b20',
					'imageURL'     => $imageBaseUrl . 'analyst3.jpg',
				),
				array(
					'category'     => 'Analysis',
					'subCategory'  => 'Coal',
					'title'        => 'Domestic coal production on track to hit 1 BT target by FY27',
					'timestamp'    => '26 Jan 09:45 IST',
					'readingTime'  => '4 min read',
					'icon'         => 'lightning',
					'themeColor'   => '#2c5282',
					'imageURL'     => $imageBaseUrl . 'analyst4.jpg',
				),
			),
			'editorsPick' => array(
				array(
					'label'        => 'Featured',
					'subCategory'  => 'Steel',
					'title'        => 'India steel demand to grow 8-10% in FY27 on infrastructure push',
					'timestamp'    => '29 Jan 12:00 IST',
					'readingTime'  => '6 min read',
					'icon'         => 'document',
					'themeColor'   => '#3182ce',
					'imageURL'     => $imageBaseUrl . 'editors1.jpg',
				),
				array(
					'label'        => 'Featured',
					'subCategory'  => 'Energy',
					'title'        => 'Green hydrogen push could reshape India\'s steel making...',
					'timestamp'    => '28 Jan 16:45 IST',
					'readingTime'  => '5 min read',
					'icon'         => 'arrow-up',
					'themeColor'   => '#38a169',
					'imageURL'     => $imageBaseUrl . 'editors2.jpg',
				),
				array(
					'label'        => 'Featured',
					'subCategory'  => 'Global',
					'title'        => 'China steel output cuts in 2026 could tighten global supply balance',
					'timestamp'    => '27 Jan 11:00 IST',
					'readingTime'  => '4 min read',
					'icon'         => 'trend-line',
					'themeColor'   => '#e53e3e',
					'imageURL'     => $imageBaseUrl . 'editors3.jpg',
				),
				array(
					'label'        => 'Featured',
					'subCategory'  => 'Aluminum',
					'title'        => 'Aluminum demand to surge on EV and renewable energy adoption...',
					'timestamp'    => '26 Jan 14:30 IST',
					'readingTime'  => '3 min read',
					'icon'         => 'plus-circle',
					'themeColor'   => '#805ad5',
					'imageURL'     => $imageBaseUrl . 'editors4.jpg',
				),
			),
		);
	}

	//Function for Half Cooked News API
	//Yashwant 05 Dec'22
	public function getNewsWidgetAPI(Request $request)
		{
			if($request->has('api_key') && !empty($request->input('api_key'))){
				$api_key = $request->input('api_key');
				$pageCount = 0;
				$commodityFilter = '';
				$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('pageCount') && !empty($request->input('pageCount')))
						$pageCount = $request->input('pageCount');
					
					if($request->has('commodityFilter') && !empty($request->input('commodityFilter')))
						$commodityFilter = $request->input('commodityFilter');
					
					$result = \ApiQuery::getNewsRowWidgetAPI($pageCount,$commodityFilter,$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)));
			}
		}

	public function lohaaNewsAPI(Request $request)
		{
			$result = \ApiQuery::getLohaaNews();	
			return new JsonResponse(array("status"=>array("code" => 1001, "message" => "Success"), "data"=> $result));
		}		
	
	public function insightCronAPI(Request $request)
	{
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters');
		    
		$result = \ApiQuery::getCronInsights($filters);	
		return new JsonResponse(array("status"=>array("code" => 1001, "message" => "Success"), "data"=> $result));
	}	
		
	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 getInsightDetails_8_2_2022(Request $request)
    {      
		$resourceType = "app";
		$memid = 0;  $itemID = 0;
		$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";//if coalmint then show only colamint related tenders
			}			

		}
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('is_blog') && !empty($request->input('is_blog'))){
		    $filters['is_blog'] = 'Y';
		}
		
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			$filters['itemID'] = $itemID;
		}else{
			$code = 2013;
			$message = "Invalid! itemID missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		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")));
                }
			
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}	
		//echo $memid . '--' . $itemID;
		if($memid){
		    
			if( $itemID != 0 & $memid == 116707 ){
			   // echo "s6";
                $redisKeyNameWeb = "insights_details_page_web_" . $itemID;
                $redisKeyNameApp = "insights_details_page_app_" . $itemID;
                
        		//check if the above key exists in redis DB
        		//if yes, then return the same
        		include_once "/home/steelmin/public_html/redisFn.php";
        		$flag = 0;
        		if( $resourceType != 'app' ){
        		    if(isKeyExistsInRedis($redisKeyNameWeb)){
        		        $result = json_decode(getKeyValueFromRedis($redisKeyNameWeb), true);
        		        $flag = 1;
        		    }
        		} elseif( $resourceType == 'app' ){
        		    
        		    if(isKeyExistsInRedis($redisKeyNameApp)){
        		        
        		        $result = json_decode(getKeyValueFromRedis($redisKeyNameApp), true);
        		        $flag = 1;
        		    }
        		} 
        		
        		if($flag == 0){
        		    
                    $resultDetails = \ApiQuery::getInsightsRows($memid, $source='details', $resourceType, $type='', $filters, 'post', 1,0,$this->appType);        			
        			if(count($resultDetails)>0  && $resourceType!='app'){
        				setInRedis($redisKeyNameWeb, json_encode($resultDetails[0]), 0);
        			}else{
        			    
        				setInRedis($redisKeyNameApp, json_encode($resultDetails), 0);
        			}
        		}		
			} else {
    			$resultDetails = \ApiQuery::getInsightsRows($memid, $source='details', $resourceType, $type='', $filters, 'post', 1,0,$this->appType);
    			if(count($resultDetails)>0  && $resourceType!='app'){
    				$result = $resultDetails[0];
    			}else{
    				$result = $resultDetails;
    			}
			}
			
			$code = 1001;
			$message = "Success";
			
		}else{
			///not loggedin/visitor///
			$visitorID = 0;
			if($request->has('visitorID'))
				$visitorID = $request->input('visitorID');				
			$filters['visitor_history_id'] = $visitorID;
						
			$resultDetails = \ApiQuery::getInsightsRows($memid=0, $source='details', $resourceType, $type='', $filters, 'pre', 1,0,$this->appType);
				
			if(count($resultDetails)>0 && $resourceType!='app'){
				$result = $resultDetails[0];
			}else{
				$result = $resultDetails;
			}
			$code = 1001;
			$message = "Success";
		}		
		
		$accessType = 'pre';
		if($memid){
			$user = new User($memid, $this->appType);
			$isAccessible =  $user->isAccessible($resourceType);//, $section='Insights'
			
			if ($isAccessible==-1) {
				$accessType = 'post';
				if(Session::has('userService') && (Session::get('userService') == 'Standard'  || Session::get('userService') == 'Free Trial'))
					$chkVisitHistoryCount = $this->appType=='CM'?1:10;
				elseif(Session::has('userService') && (Session::get('userService') == 'Price Only'))
					$chkVisitHistoryCount = $this->appType=='CM'?1:2;
			}else{
				$accessType = 'pre';
			} 
		}
		///not loggedin/visitor///
		$visitorID = 0;$preCount=0;
		
		
		
		if((($request->has('visitorID') || $memid>0) && $accessType=='pre') || ($accessType == 'post' && $chkVisitHistoryCount > 0)) {
			if(($request->has('visitorID') || $memid>0) && $accessType=='pre'){
				$visitorID = $request->input('visitorID');		
				$chkVisitHistoryCount = $this->appType=='CM'?1:2;
			}			
			
			$common = new Common();
			$preCount = $common->getVisitorCountPerWeek($section='insight', $resourceType, $this->appType, $memid, $visitorID, $visitedItem='');
			
			if(count($result)>0){
				if($resourceType!='app'){
					$result["totalAlreadyViewed"] = $preCount; 
					$result["totalAllowedToView"] = $chkVisitHistoryCount;
				}else{
					$result[0]["totalAlreadyViewed"] = $preCount; 
					$result[0]["totalAllowedToView"] = $chkVisitHistoryCount;
				}
			}
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
		}
		
	    return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }	

	public function getInsightDetails(Request $request)
    {      
		$resourceType = "app";
		$memid = 0;
		$filters = array();
		$shareText = "Download SteelMint mobile application: https://www.steelmint.com/apps.php";
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
   				$this->appType = "CM";//if coalmint then show only colamint related tenders
				$shareText = "Download SteelMint mobile application: https://www.steelmint.com/apps.php";
			}			

		}
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('is_blog') && !empty($request->input('is_blog'))){
		    $filters['is_blog'] = 'Y';
		}
		if($request->has('selected_market') && !empty($request->input('selected_market'))){
		    $filters['selected_market'] = $request->input('selected_market');
		}
		
		
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			$filters['itemID'] = $itemID;
		}else{
			$code = 2013;
			$message = "Invalid! itemID missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		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")));
                }
			
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}	
		
		
		if($memid){
            //handle blank selected_market case 
			if(empty($filters['selected_market']) && $resourceType=='app' && !empty($memid)){
                $user = new User($memid, $this->appType);
                $filters['selected_market'] =  $user->getMarketForAPPByItemID($resourceType,$itemID,'insights');                
			}
			$resultDetails = \ApiQuery::getInsightsRows($memid, $source='details', $resourceType, $type='', $filters, 'post', 1,0,$this->appType);
			if(count($resultDetails)>0  && $resourceType!='app'){
				$result = $resultDetails[0];
			}else{
				$result = $resultDetails;
			}
			$code = 1001;
			$message = "Success";
			
		}else{
			///not loggedin/visitor///
			$visitorID = 0;
			if($request->has('visitorID'))
				$visitorID = $request->input('visitorID');				
			$filters['visitor_history_id'] = $visitorID;
						
			$resultDetails = \ApiQuery::getInsightsRows($memid=0, $source='details', $resourceType, $type='', $filters, 'pre', 1,0,$this->appType);
				
			if(count($resultDetails)>0 && $resourceType!='app'){
				$result = $resultDetails[0];
			}else{
				$result = $resultDetails;
			}
			$code = 1001;
			$message = "Success";
		}		
		 if($filters['debug']=="1"){     
            echo "<pre>";
            print_r(session()->all());
            echo "----->".$isAccessible;
            echo "</pre>";
        }
		$accessType = 'pre';
		if($memid){
			$user = new User($memid, $this->appType);
			//$isAccessible =  $user->isAccessible($resourceType);//, $section='Insights'
			$isAccessible = $user->isAccessible($resourceType,'Prices','','','',$filters['selected_market']);
               
			if ($isAccessible==-1) {
				$accessType = 'post';
				if(Session::has($filters['selected_market']) && 
                  (
                    Session::get($filters['selected_market'])['userService'] == 'Corporate Standard' ||  Session::get($filters['selected_market'])['userService'] == 'Standard'  ||  Session::get($filters['selected_market'])['userService'] == 'Free Trial')
                 )
					$chkVisitHistoryCount = $this->appType=='CM'?1:10;
				elseif(Session::has($filters['selected_market']) && (Session::get($filters['selected_market'])['userService'] == 'Price Only'))
					$chkVisitHistoryCount = $this->appType=='CM'?1:2;
			}else{
				$accessType = 'pre';
			} 
		}
		///not loggedin/visitor///
		$visitorID = 0;$preCount=0;
		if((($request->has('visitorID') || $memid>0) && $accessType=='pre') || ($accessType == 'post' && $chkVisitHistoryCount > 0)) {
			if(($request->has('visitorID') || $memid>0) && $accessType=='pre'){
				$visitorID = $request->input('visitorID');		
				$chkVisitHistoryCount = $this->appType=='CM'?1:2;
			}			
			
			$common = new Common();
			$preCount = $common->getVisitorCountPerWeek($section='insight', $resourceType, $this->appType, $memid, $visitorID, $visitedItem='');
			
			if(count($result)>0){
				if($resourceType!='app'){
					$result["totalAlreadyViewed"] = $preCount; 
					$result["totalAllowedToView"] = $chkVisitHistoryCount;
				}else{
					$result[0]["totalAlreadyViewed"] = $preCount; 
					$result[0]["totalAllowedToView"] = $chkVisitHistoryCount;
				}
			}
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result,"shareText" => $shareText));
		}
		
	    return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result,"shareText" => $shareText));
    }	
	
	public function getInsightDetailsOLD(Request $request)
    {      
		$resourceType = "app";
		$memid = 0;
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters');
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			$filters['itemID'] = $itemID;
		}else{
			$code = 2013;
			$message = "Invalid! itemID missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		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")));
                }
			
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}	
		
		
		if($memid){
			
			$resultDetails = \ApiQuery::getInsightsRows($memid, $source='details', $resourceType, $type='', $filters, 'post');
			if(count($resultDetails)>0  && $resourceType!='app'){
				$result = $resultDetails[0];
			}else{
				$result = $resultDetails;
			}
			$code = 1001;
			$message = "Success";
			
		}else{
			///not loggedin/visitor///
			$company='SteelMint';
			$sender ='';
			$lan_ip ='';
			$parent ='';
			$_sender_agent ='';
			$platform ='';
			$device ='';
			if($resourceType=='web'){	
								
				/* $browser = get_browser(null, true);
				$_sender = $browser['parent'];
				$platform = $browser['device_type'];
				$device = $browser['platform'];
				$_sender_agent = $browser['browser_name_pattern']; */
			
				if($request->has('sender'))
					$sender = $request->input('sender');
				if($request->has('tokinx'))
					$lan_ip = $request->input('tokinx');	
				if($request->has('parent'))
					$parent = $request->input('parent');
				
				
				if($request->has('browser_name_pattern'))
					$_sender_agent = $request->input('browser_name_pattern');
				if($request->has('deviceType'))
					$platform = $request->input('deviceType');	
				if($request->has('platform'))
					$device = $request->input('platform');
			}else{
				if($request->has('deviceID'))
					$parent = $request->input('deviceID');
				if($request->has('fcmToken'))
					$_sender_agent = $request->input('fcmToken');
				if($request->has('deviceType'))
					$device = $request->input('deviceType');	
				$platform = "Mobile APP";
			}
				if($request->has('ip'))
					$ip = $request->input('ip');
				else
					$ip =  $_SERVER['REMOTE_ADDR'] ; 
				///include_once("/home/steelmin/public_html/hf.php");
				$ip_country = ipTocntry("$ip");
				
				$creden = DB::table('tb1_visitor_history')
									->select(array('id'))
									->where('ip_country', '=', $ip_country )
									->where('ip_address', '=', $ip )
									->where('lan_ip', '=', $lan_ip )
									->where('device_id', '=', $parent )
									->where('device', '=', $_sender_agent )
									->where('device_name', '=', $device )
									->where('platform', '=', $platform )
									->where('company', '=', 'SteelMint' )
									->first();
				
				$visitor_iid = (isset($creden['id']))?$creden['id']:0;
				if($visitor_iid==0){
					$_data = array(
							'mem_id' => $memid,
							'log_date' => $GLOBALS['currDate'],
							'log_time' => $GLOBALS['currDateTime'],
							'ip_country' => $ip_country,
							'ip_address' => $ip,						
							'lan_ip' => $lan_ip,
							'device_id' => $parent,
							'device' => $_sender_agent,
							'device_name' => $device,
							'company' => $company,
							'platform' => $platform	
							);
					
					$visitor_iid = DB::table('tb1_visitor_history')
						->insertGetId($_data); 
				}
				
			$filters['visitor_history_id'] = $visitor_iid;
			//}
			
			$resultDetails = \ApiQuery::getInsightsRows($memid=0, $source='details', $resourceType, $type='', $filters, 'pre');
				
			if(count($resultDetails)>0 && $resourceType!='app'){
				$result = $resultDetails[0];
			}else{
				$result = $resultDetails;
			}
			$code = 1001;
			$message = "Success";
		}		
		
	    return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }
	
	public function getRecetViewMostread(Request $request)
	{
		
	}
	
	//as prem update the concept to open it for all visitor + loggendin user
	public function updateMostread(Request $request){
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			
			$post_id = 0;
			$count = 1;

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

			if($request->has('count') && (int)$request->input('count') > 0) {
				$count = $request->input('count');
			} 

			$sql = "UPDATE `tbl_news_post` SET `most_read` = (`most_read` + " . (int)$count . ") WHERE `post_id` = " . (int)$post_id;

			DB::statement($sql);
			/*code added to update most read in tbl_intel_insight_hashmap - 
			* Added on 29aug2021
			*/
			$update =	"UPDATE tbl_intel_insight_hashmap AS to_update
							INNER JOIN tbl_news_post AS update_from
							ON 	to_update.post_id = ".(int)$post_id."
							AND update_from.post_id = ".(int)$post_id."		
							SET to_update.most_read = update_from.most_read";
			DB::statement($update);
			$code = 1001;
			$message = "Updated successfully";
		}else{
			$code = 2013;
			$message = "Invalid not found.";
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	}

	public function chkPostToSiteMap(Request $request){
		//$message = \ApiQuery::addPostToSiteMap(159352, "infographics");
		//$message = \ApiQuery::updatePackageIDForApp(2);
return new JsonResponse(array("code" => $code, "message" => $message));		
	}
	
	public function updateMostreadOLD(Request $request)
    {
		$resourceType = "app";
		
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
		
			if($resourceType=='web'){
				if($request->has('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")));
                }
					
					//$memid = _encrypt_decrypt($action='decrypt', $memid);
					$auth = new authentication();
					$user_id = $auth->authUserId($memid);//for web user
					if ($user_id) {
						$post_id = 0;
						$count = 1;

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

						if($request->has('count') && (int)$request->input('count') > 0) {
							$count = $request->input('count');
						}

						$sql = "UPDATE `tbl_news_post` SET `most_read` = (`most_read` + " . (int)$count . ") WHERE `post_id` = " . (int)$post_id;

						DB::statement($sql);
						$code = 1001;
						$message = "Updated successfully";
					}else{
						$code = 2100;
						$message = "Unauthorized action.";
					}
				}else{
					$code = 2100;
					$message = "Unauthorized action.";
				}
			}else{	
				if ($request->has('accessToken') && $request->input('accessToken')!='') {
				   // $auth = new authentication();
				    $token = $request->input('accessToken');
					$auth = new authentication();
					//$token = $request->input('token');
					$user_id = $auth->authToken($token,$this->appType);
					if ($user_id) {
						$us = new User($user_id);
						//$userAccess = $us->getTakenServicesByUser();
					} else {
						 return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action. Token access denied"))) ;
					}

					$post_id = 0;
					$count = 1;

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

					if($request->has('count') && (int)$request->input('count') > 0) {
						$count = $request->input('count');
					}

					$sql = "UPDATE `tbl_news_post` SET `most_read` = (`most_read` + " . (int)$count . ") WHERE `post_id` = " . (int)$post_id;

					DB::statement($sql);
					$code = 1001;
					$message = "Updated successfully";

				}else{
					$code = 2100;
					$message = "Unauthorized action.";
				}
			}
		}else{
			$code = 2013;
			$message = "Invalid not found.";
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		//return new JsonResponse(array("code" => $code, "message" => $message));
    }
	
	
	public function removeSpecialChars($content) {
        // Convert to UTF-8 (if not already) and remove invalid characters
        $content = mb_convert_encoding($content, 'UTF-8', 'UTF-8');
    
        // Remove non-printable and non-ASCII characters
        $content = preg_replace('/[^\x20-\x7E]/u', '', $content);
    
        return $content;
    }
	
	//post -> new/editand delete
	public function postInsight(Request $request)
    {
		$actionType='new_post';
		if($request->has('action'))
			$actionType = strtolower($request->input('action'));
		
		if($request->has('postID') && !empty($request->input('postID'))){
		    $postID = $request->input('postID');
		//echo $actionType;
		
			if($request->has('postDataFilePath') || strtolower($actionType)=='delete'){
				$filePath = $request->input('postDataFilePath');
				
				if(strtolower($actionType)=='delete'){
					$section = $request->input('section');
					switch($section){
						case "insight":
							$tblName = 'tbl_news_post';
						break;
						case "infographs":
						case "infograph":
							$tblName = 'tbl_stats_infographics';							
						break;
						case "intel":
							$tblName = 'intel';
						break;
					}
					//echo '137899'.'::'.$tblName.'::'.$postID;
					if($tblName!='' && $postID >0){
						DB::table($tblName)
							->where('post_id', '=', $postID )
							->delete();	
				// 		DB::table('tbl_intel_insight_hashmap')
				// 			->where('post_id', '=', $postID )
				// 			->delete();	
				
                        //update updated_at column of tbl_intel_insight_hashmap table
                        $hmData =array(
                        			'processed'=> 3,
                        			'isDeletedPost' => 'y'
                        		);
                        DB::table('tbl_intel_insight_hashmap')
                        	->where('post_id', '=', $postID )
                        	->update( $hmData );				
				
				
						$code = 1001;
				        $message = "Deleted successfully";
					}
				}else{
					$postData = file_get_contents($filePath);
					$jsonData = json_decode($postData, true);
					
					$post = $jsonData['post_data'];
					
					///$authorData = $post['updated_by_author'];					
					/*$uData = array(
						"json"=>$postData,
						"actionType"=>strtolower($actionType),
						"file"=>$filePath,
						"postID"=>$postID
					);
					///print_r($post);	
					DB::table('tbl_post_test')
							->insert($uData) ;
					*/
					$post_id = (int)$postID;
					$post_title = '';
					$post_content = '';
					$category = '';
					$sub_category = '';
					$author_name = '';
					$author_id = '';
					$href = '';
					$image = '';
					$medium_image = '';
					$small_image = '';
					$sponsored = '';
					$post_date = '';
					$post_time = '';
					$region = '';
					$industry_type = '';
					$coal_sub_categories = '';
					$for_smgroup_company = '';
					$meta_description = '';
					$video_image_url = '';
					$videoThumbnailImage = '';
					
					if(isset($post['title'])) {
						$post_title = addslashes($post['title']);
					}
					if(isset($post['tag_name'])) {
						$post_tags = $post['tag_name'];
					}
					if(isset($post['article_category'])) {
						$article_category = $post['article_category'];
					}

					if(isset($post['description'])) {
						/* Commented (below 2 lines) on 16sep2025 
						 * because it was adding extra tags 
						 * like  <p><p><ul></p><p> <li>China leading.... 
						 * in the post data 
						 * */
						$post_content = "<p>" . str_replace("\r\n", "</p><p>", $post['description']) . "</p>";
						$post_content = "<p>" . str_replace("</p><p></p><p>", "</p><p>", $post_content) . "</p>";
						//$post_content = str_replace("<p></p>", "", $post_content);
						
						//$post_content = addslashes($post_content);
						//$post_content = str_replace("<table", '<div class=\"ibox-content table-responsive\"><div class=\"table-responsive\"><table', $post_content);
						//$post_content = str_replace("</table>", '</table></div></div>', $post_content);
						$post_content = preg_replace('#<div class="sharedaddy sd-sharing-enabled"(.|\s)+</div>#', '', $post_content);
					}

					if(isset($post['commodity'])) {
						$category = addslashes($post['commodity']);
					}

					if(isset($post['sub_commodity'])) {
						$sub_category = addslashes($post['sub_commodity']);
					}

					if(isset($post['authors_name'])) {
						$author_name = addslashes($post['authors_name']);
					}
					
					if(isset($post['author'])) {
						$author = addslashes($post['author']);
						$author_id = addslashes($post['author_id']);
					}

					if(isset($post['for_smgroup_company'])) {
						//$for_smgroup_company = addslashes($post['for_smgroup_company']);
						$for_smgroup_company = implode(",", $post['for_smgroup_company']);
					}
					
					if(isset($post['url'])) {
						//if( $for_smgroup_company == 'steelmint.com' )
						//$post['url'] = str_replace("/news/", "/insights/", $post['url']);
						$post['url'] = str_replace("https://www.steelmint.in/", "https://www.bigmint.co/insights/detail/", $post['url']);
						$href = addslashes($post['url']);
						$full_url = addslashes($post['url']);
					}

					if(isset($post['full_image'])) {
						$image = addslashes($post['full_image']);
					}

					if(isset($post['medium_image'])) {
						$medium_image = addslashes($post['medium_image']);
					}
					
					if(isset($post['small_image'])) {
						$small_image = addslashes($post['small_image']);
					}

					if(isset($post['sponsored'])) {
						$sponsored = addslashes($post['sponsored']);
					}

					if(isset($post['region'])) {
						$region = addslashes($post['region']);
					}

					if(isset($post['industry_type'])) {
						$industry_type = addslashes($post['industry_type']);
					}

					if(isset($post['coal_sub_categories'])) {
						$coal_sub_categories = addslashes($post['coal_sub_categories']);
					}

					if( $for_smgroup_company == '' )
							$for_smgroup_company = "steelmint.com";
					
					if(isset($post['meta_description'])) {
						$meta_description = addslashes($post['meta_description']);
					}

					if(isset($post['date'])) {
						$post_date = addslashes($post['date']);
					}

					if(isset($post['post_time'])) {
						$post_time = addslashes($post['post_time']);
					}
					
					if(isset($post['featured_url'])) {
						$featured_url = addslashes($post['featured_url']);
					}
					
					if(isset($post['video_image_url'])) {
						$video_image_url = addslashes($post['video_image_url']);
					}
					
					$section='';
					$commodityID=0;					
					$locationID=0;						
					$companyID=array();	//multi ids
					$industryID=array();//multi ids
					$trendingID=array();//multi ids
					$sponsored='';//multi ids
					$featured_image='';
					$slider_image='';
					$listing_image='';
					//print_r($post['extra_info']);
					if(isset($post['extra_info'])) {
						$extra_info = ($post['extra_info']);
						
						if(isset($extra_info['section'])) {
							$section = ($extra_info['section']);
						}
					
						if(isset($extra_info['commodity'])) {
							$commodity = ($extra_info['commodity']);
							$commodityID = $commodity['id'];
							//foreach($commodity as $a)
							//	$commodityID[] = $a['id'];
							if($commodityID){
							    $sqlRCMResult = DB::table('tbl_region_commodity_master')
							        ->select('ID','parentID', 'grandParentID', 'itemName')
							        ->where('ID' , $commodityID)
			                    	//->orWhere('parentID' , $commodityID)
							       // ->orWhere('grandParentID' , $commodityID)
						            ->first();
						      if($sqlRCMResult['grandParentID']>0)
						       {
						           $commodityID = $sqlRCMResult['grandParentID'];
						           $subCommodityID = $sqlRCMResult['parentID'];
						           $subSubCommodityID = $sqlRCMResult['ID'];
						       }elseif($sqlRCMResult['parentID']>0){
						            $commodityID = $sqlRCMResult['parentID'];
						             $subCommodityID = $sqlRCMResult['ID'];
						            $subSubCommodityID = 0;
						       }else{
						           $commodityID = $sqlRCMResult['ID'];
						           $subCommodityID = 0;
						           $subSubCommodityID = 0;
						       }
							   
							   if($sqlRCMResult['parentID']>0 && $section=='insight'){
									$sqlRCMResult1 = DB::table('tbl_region_commodity_master')
										->select('itemName')
										->where('ID' , $sqlRCMResult['parentID'])
										->first();
						      
									$sub_category = $sqlRCMResult['itemName'];
									$category = $sqlRCMResult1['itemName'];
							   }
						    }
						}
						
						if(isset($extra_info['location'])) {
							$location = ($extra_info['location']);
							$locationID = $location['id'];
							
							if($section=='insight' || $section=='intel'){
								$locationtitle = $location['title']; 
								list($c, $s, $countryName) = explode(" :: ", $locationtitle);
								
								if($locationID ==  ""){
									$sqlRCMRegion = DB::table('tbl_country')
												->select('id', 'f_region')
												->where('country' , trim($countryName))
												->first();
									$countryID = $sqlRCMRegion['id'];
									
									$sqlRCMRegion = DB::table('tbl_state_city')
													->select('id')
													->where('country_id' , $countryID)
													->where('state_name' , $s)
													->where('city_name' , $c)
													->first();
									$locationID = $sqlRCMRegion['id'];				
									//$region = $sqlRCMRegion['f_region'];
								} /* else {
									$sqlRCMRegion = DB::table('tbl_state_city')
												->select('country_id')
												->where('id' , $locationID)
												->first();
									$countryID = $sqlRCMRegion['country_id'];
									$sqlRCMRegion = DB::table('tbl_country')
												->select('f_region')
												->where('id' , $countryID)
												->first();
									$region = $sqlRCMRegion['f_region'];			
								} */
							}
							
							$continentID = DB::table('tbl_state_city')
												->select('continentID')
												->where('id' , $locationID)
												->first();
						}
						
						if(isset($extra_info['company'])) {
							$company = ($extra_info['company']);
							foreach($company as $a)
								$companyID[] = $a['id'];
						}
						
						if(isset($extra_info['industry'])) {
							$industry1 = ($extra_info['industry']);
						
							foreach($industry1 as $a){
								$industryID[] = $a['id'];
							}
							
						}
					
						if(isset($extra_info['trending'])) {
							$trending = ($extra_info['trending']);
							foreach($trending as $a)
								$trendingID[] = $a['id'];
						}
						
						if(isset($extra_info['featured_image'])) {
						    $featured_image = addslashes($extra_info['featured_image']);							
						}
						$is_blog = '';
						if(isset($extra_info['is_blog'])) {
						    $is_blog = $extra_info['is_blog'];							
						}
						
						if(isset($extra_info['slider_image'])) {
							$slider_image = addslashes($extra_info['slider_image']);							
						}
						
						if(isset($extra_info['listing_image'])) {
							$listing_image = addslashes($extra_info['listing_image']);							
						}
						
						if(isset($extra_info['sponsored'])) {
							$sponsored = addslashes($extra_info['sponsored']);							
						}
					}
					
					//$post_date_time = date('Y-m-d H:i:s', strtotime($post_date . " " . $post_time . " +5 hours 30 minutes") );
					
					///$post_date_time = date('Y-m-d H:i:s', strtotime($post_date . " +5 hours 30 minutes") );
					$post_date_time = date('Y-m-d H:i:s', strtotime($post_date) );
					$post_arr=explode(' ', $post_date_time);
					//print_r($commodityID);
					$f_timetoread = '';
					$f_timetoread =  \ApiQuery::get_read_time($post_content);
					
					if( $post_id >= 424534 ){
			         //   $post_content = str_replace("https://aws.steelmint.com/", "https://wp-insights-sm.s3.ap-south-1.amazonaws.com/", $post_content);
			         //   $href = str_replace("https://aws.steelmint.com/", "https://www.steelmint.com/insights/", $href);

			            $post_content = str_replace("https://www.steelmint.in/", "https://wp-insights-sm.s3.ap-south-1.amazonaws.com/", $post_content);
			            $href = str_replace("https://www.steelmint.in/", "https://www.bigmint.co/insights/detail/", $href);
					}
					
					$post_title = $this -> removeSpecialChars($post_title);
					$post_content = $this -> removeSpecialChars($post_content);
					$post_tags = $this -> removeSpecialChars($post_tags);
					$post_content = preg_replace('/((<p>(&nbsp;|\s)*<\/p>)|(&nbsp;|\s))+$/i', '', $post_content);
					
					switch($section){
						case "insight":
							$post_content = '<link href="https://www.steelmint.com/css/wp_style.css" rel="stylesheet" type="text/css"/>' . $post_content;
							
						
							$tblName = 'tbl_news_post';
							$uData = array(
								'post_id'=>$post_id,
								'post_title'=>htmlspecialchars($post_title, ENT_QUOTES),
								'post_content'=> htmlspecialchars($post_content, ENT_QUOTES),
								'category'=>$category,
								'sub_category'=>$sub_category,
								'author_name'=>$author_name,
								'href'=>$href,
								'image'=>$image,
								'medium_image'=>$medium_image,
								'small_image'=>$small_image,
								'sponsored'=>$sponsored,
								'post_date'=>$post_arr[0],
								'post_time'=>$post_arr[1],
								'region'=>$region,
								'industry_type'=>implode(',', $industryID),
								'for_smgroup_company'=>$for_smgroup_company,
								'meta_description'=>$meta_description,
								'featured_url'=>$featured_image,
								'video_image_url'=>$video_image_url,
								'full_url'=>$full_url,
								'post_tags'=>$post_tags,
								'article_category'=>$article_category,
								'commodityId'=>$commodityID,
								'subCommodityId'=>$subCommodityID,
								'subSubCommodityID'=>$subSubCommodityID,
								'cityID'=>$locationID,
								'trending_tag'=>implode(',', $trendingID),
								'author_id'=>$author_id,
								'author'=>$author,
								'companyID'=>implode(',', $companyID),
								'continentID'=> $continentID,
								'is_blog'=> $is_blog,
								'created_at'=>$GLOBALS['currDateTime'],
								'f_timetoread'=> $f_timetoread
							);
						break;
						case "infographs":
						case "infograph":
							$tblName = 'tbl_stats_infographics';			
							$uData = array(
								'post_id'=>$post_id,
								'post_title'=> $post_title,
								'post_content'=>$post_content,
								//'author_name'=>$author_name,
								'href'=>$href,
								'post_date'=>$post_arr[0],
								'post_time'=>$post_arr[1],							
								'accessibleToPreLogin'=>'n',
								'openedForPreLoginBy'=>'n',
								'meta_description'=>$meta_description,
								'slider_image'=>$slider_image,
								'listing_image'=>$listing_image,
								'description_image'=>$featured_image,
								'post_tags'=>$post_tags,					  
								'article_category'=>$article_category,
								'commodityId'=>$commodityID,
								'subCommodityId'=>$subCommodityID,
								'subSubCommodityID'=>$subSubCommodityID,
								'for_smgroup_company'=>$for_smgroup_company,
								///'cityID'=>$cityID,
								'author_id'=>$author_id,
								'author'=>$author,
								'created_at'=>$GLOBALS['currDateTime']
								///'trending_tag'=>$trending_tag
							);						
						break;
						case "intel":

							$tblName = 'intel';
							$type='image';
							if($video_image_url!='')
							    $type='video';
							$uData = array(
								'post_id'=>$post_id,
								'title'=>htmlspecialchars($post_title, ENT_QUOTES),
								'description'=> htmlspecialchars($post_content, ENT_QUOTES),
								'videoUrl'=>$video_image_url,
								'imageUrl'=>$featured_image,
								'videoThumbnailImage'=>$videoThumbnailImage,
								'datePublished'=>$post_date_time,
								'type'=>$type,
								'isAd'=>'n',
								'f_tags'=>$post_tags,
								'article_category'=>$article_category,
								'url_screen_name'=>$full_url,
								///'post_tags'=>$post_tags,
								'commodityID'=>$commodityID,
								'subCommodityID'=>$subCommodityID,
								'subSubCommodityID'=>$subSubCommodityID,
								'for_smgroup_company'=>$for_smgroup_company,
								'cityID'=>$locationID,
								'author_id'=>$author_id,
								'author'=>$author,
								'trending_tag'=>implode(',', $trendingID),
								'created_at'=>$GLOBALS['currDateTime'],
								'f_timetoread'=> $f_timetoread
							);	
						break;
					}
					
					///start publishing the post on each edit and new from 18Nov2021 post_status
					
					$tempVar = serialize($jsonData) . "-";
					
					if(isset($jsonData['post_status'])){
						$tempVar = 's1-';
						if($jsonData['post_status']=='publish'){
						    $tempVar = 's2-';
							$creden = DB::table($tblName)
										->select("post_id")
										->where('post_id', '=', $postID )
										->first();
							$isExists = (isset($creden['post_id']))?$creden['post_id']:0;					
							$tempVar = 's3-$isExists-';
							if( $isExists == 0 ){
							    $tempVar = 's4-$tblName-';
								//DB::enableQueryLog();
								$lastInsertedId = DB::table($tblName)->insertGetId($uData);
                                $tempVar = 's5-$lastInsertedId-';
//								DB::table($tblName)
//									->insert($uData) ;
								$tempVar = 's4-';	
								//dd(DB::getQueryLog());
								$hmData =array(
											'post_id'=>$post_id,
											'f_section'=>$section,
											'commodityID'=>$commodityID,
											'subCommodityID'=>$subCommodityID,
											'subSubCommodityID'=>$subSubCommodityID,
											'post_created_date'=>$post_arr[0],
											'post_created_time'=>$post_arr[1],
											'f_datetime'=>$GLOBALS['currDateTime']
										);
										
								if($section=='insight' || $section=='intel'){
									DB::table('tbl_intel_insight_hashmap')
										->insert($hmData) ;
								}
							}else{
								unset($uData['created_at']); 
								DB::table($tblName)
								->where('post_id', '=', $postID )
								->update( $uData );
								
								//update updated_at column of tbl_intel_insight_hashmap table
                                $hmData =array(
                                			'updated_at'=> $GLOBALS['currDateTime'],
                                			'processed'=> 3
                                		);
                                
                                
                                DB::table('tbl_intel_insight_hashmap')
                                	->where('post_id', '=', $postID )
                                	->update( $hmData );								
								
							}
						}
					}
					///end publishing the post on each edit and new from 18Nov2021 post_status
					
					$code = 1001;
			    	$message = "Saved successfully $postID-$tempVar-$filePath-/$/";
					
				}
				
			}else{//on delete
				
			}
		}else{
			$code = 2013;
			$message = "Invalid post.";
		}
		if($section ==  "insight" || $section ==  "insights")
			\ApiQuery::actionsPostInsightPublish($postID, $locationID);
		else if($section ==  "infographs" || $section ==  "infograph" ){
			\ApiQuery::actionsPostInfographicsPublish($postID);
		}
		else if($section ==  "intel" )
			\ApiQuery::actionsPostIntelPublish($postID);
		
		
		if($section ==  "insight" || $section ==  "insights" || $section ==  "intel")
			\ApiQuery::create_json_for_region();
		
		//return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		return new JsonResponse(array("code" => $code, "message" => $message));
    }
	
	public function getIntelInsights(Request $request)
    {      
		$memid=0;
		$resourceType='app';
		$result = array();	
		$shareText = "Download SteelMint mobile application: https://www.steelmint.com/apps.php";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		//$memId = \App\Helper::getMemId();
		$commodityID = array();
		if($request->has('commodityID'))
			$commodityID = $request->input('commodityID');
		
		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")));
                }
			
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}
		
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
		    
            if($filters['selected_market']=='future_prices')
                $filters['selected_market']='';
            
			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
			   
				$this->appType = "CM";//if coalmint then show only colamint related tenders
				$shareText = "Download CoalMint mobile application: https://www.coalmint.com/apps.php";
			}			
			///cphrase code
			if( isset($filters['searchTerms'])){
				$common = new Common();
				$innerFilterCond = $common->getSearchTermFilterCond($filters['searchTerms'], 'insight');
				
				if(!empty($innerFilterCond)){
					unset($filters['searchTerms']);
			    }
			    if(isset($innerFilterCond['commodity']) && !empty($innerFilterCond['commodity']) && ($innerFilterCond['commodity']!='all')){
					$filters['commodityID'] = array($innerFilterCond['commodity']);
				}
				if(isset($innerFilterCond['location']) && !empty($innerFilterCond['location']) && ($innerFilterCond['location']!='all')){
					$filters['regionID'] = array($innerFilterCond['location']);
				}				
			}///
		}
		
		if($request->has('regionID')){
			$filters['regionID'] = $request->input('regionID');
		}
		
		if($request->has('source')){
			$filters['source'] = $request->input('source');
		}
		$filters['resourceType'] = $resourceType;
		$offset=0;
		$pageValue=1;
		
		if ($request->has('pageValue') && $request->input('pageValue')!=''){
			$pageValue = $request->input('pageValue');	
			if(isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard') {
		        $offset = ($pageValue-1)* 10;		
		    } else 
			    $offset = ($pageValue-1)* DEFAULT_NEWS_LIMIT;
		}
		
		$result = \apiQuery::getIntelInsightsList($memid, $commodityID, $offset, $filters); 

// check if restricitons is applied for intel/insights 
// ##############
//##############
//		##############
//check restriction for intel
	if ($memid != '' && $memid != 0) {
		$package = DB::table("tbl_updated_reg_logs_bm")
					->select(DB::raw('group_concat(active_products) as prodIds'))
					->where("memid","=",$memid)
					->where("status","=","Active");
        
        $selected_market='';
        if(isset($filter['selected_market'])){
            $selected_market = $filter['selected_market'];
        }
        if($selected_market != '')
                $package = $package->whereRaw("FIND_IN_SET('$selected_market', f_market)");
                        
		if($this->appType=='CM'){
			$package = $package->where("services","=","C")->first();
		}else{
			if($resourceType == "web")
				$package = $package->where("services","=","W")->first();

			if($resourceType == "app")
			   $package = $package->whereIn("services",["W", "MA", "MA_PO"])->first();
		}
		if(empty($package["prodIds"])){
			$limitIntel = "Y";
		}

		if(!empty($package["prodIds"])){
			$pkids = explode(",",$package["prodIds"]);
			
			$package_intel_accesible_count = DB::table("tbl_packages")->whereIn("id",$pkids)->where("is_intel_accessible","=","Y")->count();
			
			if($package_intel_accesible_count == 0){
				$limitIntel = "Y";
			} else {
				$limitIntel = "N";
			}
		}
	}else {
		$limitIntel = "Y";
	}

//check restriction for insights
	if ($memid != '' && $memid != 0) {
		$user = new User($memid, $this->appType);
		//$isAccessible =  $user->isAccessible($resourceType);//, $section='Insights'
		$isAccessible =  $user->isAccessible($resourceType,'Insights','','','',$filters['selected_market']);//, $section='Insights'
		
		if ($isAccessible==-1) {
			if(Session::has($filters['selected_market']) && 
                (Session::get($filters['selected_market'])['userService'] == 'Standard' || 
                'Corporate Standard'==Session::get($filters['selected_market'])['userService'] || Session::get($filters['selected_market'])['userService'] == 'Free Trial'
                )
            ){
				$limitInsight = "Y";
			}elseif(Session::has($filters['selected_market']) && Session::get($filters['selected_market'])['userService'] == 'Price Only'){
				$limitInsight = "Y";
			} else		
				$limitInsight = "N";
		}else{
			$limitInsight = "Y";
		} 
	}else {
		$limitInsight = "Y";
	}
// check if restricitons is applied for intel/insights 
// ##############
//##############
//		##############
		
		$code = 1001;
		$message = "Success";
        if(isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard' && count($result)>0) {
            
            $ex = $result;
            $result = array();
            $result = $ex["dataValue"];
            $cntValue = $ex["cntValue"];
        }elseif(isset($filters['API_Key']) && $filters['API_Key'] == '1dP9kOjmxZDt1' && count($result)==0) {
              return new JsonResponse(array("status"=>array("code" => 2001, "message" => "You are not authorized to access more than 1-week data at a time.")));
        }
        else {
			if(count($result)<1)
				$result = array();
            $cntValue = 0;
        }
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result, "limitInsight"=> $limitInsight, "limitIntel"=> $limitIntel, "cntValue"=> $cntValue,"shareText" => $shareText));
	}
	
	public function getIntelInsightsSMAPI(Request $request)
    {
		$fromdate = '';
		$todate = '';
		$commodityIDFilter = '';
		$regionIDFilter = '';
		$appType = 'SM';
		
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		   $filters = $request->input('filters');
			if(isset($filters['API_Key']) && !empty($filters['API_Key'])){
				if(!isset($filters['API_from_date']) || empty($filters['API_from_date']) || !isset($filters['API_to_date']) || empty($filters['API_to_date'])){
					$code = 2001;				
					$message = "Both fromdate and todate are mandatory for calling API";
					return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
				}
				$fromdate = $filters['API_from_date'];
				$todate = $filters['API_to_date'];
				
				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 = $filters['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(isset($filters['appType']) && !empty($filters['appType']))
						$appType = $filters['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)));
					}
					
					if(isset($filters['commodityID']) && !empty($filters['commodityID']))
						$commodityIDFilter = $filters['commodityID'];
					
					if(isset($filters['regionID']) && !empty($filters['regionID']))
						$regionIDFilter = $filters['regionID'];
					
					$result = \ApiQuery::getNewsRowsVendorAPI($fromdate,$todate,$commodityIDFilter,$regionIDFilter,$appType,$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)));
			}
			
		}
		else{
			$code = 2001;				
			$message = "Invalid request format";
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}		
    }
	
	public function getAuthorDetails(Request $request)
    {      
		$resourceType = "app";
		$memid = 0;
		$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";//if coalmint then show only colamint related tenders
			}			

		}
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$postType='insight';
		if($request->has('postType'))
			$postType = strtolower($request->input('postType'));
		
		if($postType=='blog')
			$filters['is_blog'] = 'Y';
		
		if($request->has('is_blog') && !empty($request->input('is_blog'))){
		    $filters['is_blog'] = 'Y';
		}
		$itemID=0;
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			
			$result = DB::table('tbl_rel_manager')
								->select('RM_name', 'RM_email', 'imageURL', 'facebookId','twitterId','linkedIn','description')
								->where('id', '=', $itemID )
								->first();
			if($result){
				$result['relatedPost']=array();
				$filters['authorID'] = $itemID;
				if('insight'==$postType || 'blog'==$postType){
					$result['relatedPost'] = \ApiQuery::getInsightsRows($user_id=0, $source="listing", $resourceType, $type='default', $filters,'post',10, $offset=0, $this->appType);
				}elseif('infograph'==$postType){
					$tblName = 'tbl_stats_infographics';
				}else{
					$result['relatedPost'] = \ApiQuery::getIntelRowSet($memid=0,$resourceType,$type='', $filters, $pageType='post', $limits=10, $offset=0, $appType='SM');
				}
				
				$code = 1001;				
				$message = "Success";
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
			}else{
				$code = 2013;
				$message = "Invalid AuthorID.";
				
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}				
		}else{
			$code = 2013;
			$message = "Invalid! AuthorID missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
	}
	
	/* shifted this to user.php
        public function getMarketForAPPByItemID($memid,$itemID,$section='insights'){ 
        if(!empty($memid) && !empty($itemID)){
            $user = new User($memid, $this->appType);           
            $isAccessible = $user->isAccessible($resourceType,$section,'','','','');
            //getting market access for the user 
            $userMarket = array_unique(explode(",",Session::get('marketsIncludes')));
            $common = new Common();
            //getting markets of itemID
            $get_market_data = $common-> getMarketByID($itemID,strtolower($section));
            $selected_market =$get_market_data['allowed_market'][0];    
            $allowed_market = $get_market_data['allowed_market'];
            //print_r($userMarket);
            //print_r($get_market_data);
            if(!empty($allowed_market)){
                $mkt_common = array_intersect($userMarket, $allowed_market);
                //checking if getting multiple common market 
                //print_r($mkt_common);
                if(count($mkt_common)==1){
                    $selected_market = reset($mkt_common);

                }elseif(count($mkt_common)>1){
                    //step-1 checking if user has any web services of any market of itemID
                  
                    $webcheck_qry = 
                            DB::table('tbl_updated_reg_logs_bm as tbl_ulog')
                            ->select('tbl_ulog.f_market')
                            ->join('tbl_packages', function ($join) {
                                $join->on(DB::raw('FIND_IN_SET(tbl_packages.id, tbl_ulog.active_products)'), '>', DB::raw('0'));
                            })
                            ->where('tbl_ulog.services', 'W')
                            ->where('tbl_ulog.memid', $memid)
                            ->where('tbl_ulog.status', 'Active')
                            ->where(function ($query) use ($get_market_data) {
                                foreach ($get_market_data['allowed_market'] as $market) {
                                    $query->orWhereRaw('FIND_IN_SET(?, f_market)', [$market]);
                                }
                            })
                            ->orderBy('tbl_ulog.startdate', 'asc')
                            ->first();
                    if(!empty($webcheck_qry['f_market']))
                        $webcheck_mkt = array_filter(explode(',',$webcheck_qry['f_market']));
                    if(!empty($webcheck_mkt)){
                       $selected_market=$webcheck_mkt[0]; 
                      // echo "Getting From Web";
                      // print_r($webcheck_qry);
                    }
                    else{
                        //check for markets of  mobile-app active services
                         $appcheck_qry = DB::table('tbl_updated_reg_logs_bm as tbl_ulog')
                                        ->select('tbl_ulog.f_market')
                                        ->join('tbl_packages as packages', function ($join) {
                                            $join->on(DB::raw('FIND_IN_SET(packages.id, tbl_ulog.active_products)'), '>', DB::raw('0'));
                                        })
                                        ->where('tbl_ulog.services', 'MA')
                                        ->where('tbl_ulog.memid', $memid)
                                        ->where('tbl_ulog.status', 'Active')
                                        ->where(function ($query) use ($allowed_market) {
                                            foreach ($allowed_market as $market) {
                                                $query->orWhereRaw('FIND_IN_SET(?, tbl_ulog.f_market)', [$market]);
                                            }
                                        })
                                        ->orderBy('packages.fPriority', 'desc')  // Order by fPriority in descending order
                                        ->orderBy('tbl_ulog.startdate', 'asc')
                                        ->first();
                            if(!empty($appcheck_qry['f_market']))
                                $appcheck_mkt = array_filter(explode(',',$appcheck_qry['f_market']));
                            if(!empty($appcheck_mkt)){
                                $selected_market=$appcheck_mkt[0];                                
                                //echo "Getting From app";
                            }
                        
                    }
                    
                }              
                    
            }
            //echo "</pre>";
            //echo "return:".$selected_market;
            return $selected_market;
        }
	}*/
	
	
}
