<?php

//////////////////////////////////////////
///  Query class for api & website    
//////////////////////////////////////// 
//use App\Http\Controllers\Action\Common;
//use Illuminate\Support\Facades\DB;
////include_once "/home/steelmin/public_html/inc/config1.php"; 
include_once "/home/steelmin/public_html/hf.php"; 
$CM_MEMID_ALLOWED = array(56350, 120030, 120954);
$SPLRPT_MEMID_ALLOWED = array(56350,107067,34378,2,5652,100520,108704);
use App\Http\Controllers\Action\Common;
use App\Http\Controllers\Auth\User;
include_once('helper.php');
define("DEFAULT_LIMIT",15);
define("DEFAULT_LIMIT_INTEL",25);
define("DEFAULT_LIMIT_HOME",20);
define("DEFAULT_NEWS_LIMIT",20); 
define("DEFAULT_TENDERS_LIMIT",15);
define("DEFAULT_PRICES_LIMIT",20);
define("DEFAULT_REPORTS_LIMIT",15);
define("RECOMMENDED_LIMIT",4);
define("RELATED_LIMIT",4);
define("KEYPRICES_LIMIT",5);
define("siteUrl", 'https://www.bigmint.co/');
define("sitePath", '/home/steelmin/public_html/');
define("siteFolderPath", '/home/steelmin/public_html/bm/');
define("specificEventsJsonEndPoint", "https://bm-events.s3.ap-south-1.amazonaws.com/events/json/");

class apiQuery{
	
	public static function getPackageDtlsOfMemid($memid){
		$a = file_get_contents(siteUrl . "mix_panel_function.php?id=$memid");
		
		return $a;
	}
	
	public static function statTablePlot($request=array()){
		if(isset($request['resourceType']) && $request['resourceType']=='app'){
			$request["all_data"] = trim($request["all_data"],'-');
			$request["all_data"] = '-'.$request["all_data"].'-All';
		}
	    $results_per_page = 10;$datatype="";
	    $page_first_result = (($request['page'] != ""?$request['page']:1)-1) * $results_per_page;
	   
	    $comm_etc = explode("-",$request["all_data"]);
	    if($request['debug']=='Y'){
             echo "<pre>";
             print_r($comm_etc);
        }
            
		$request["all_data"] = trim($request["all_data"],'-');
	    $data = array("result"=>array(),"pages"=>1,"req"=>$request,"extra"=>"");
        $datatype = $comm_etc[0] == "coastal" ? "coastal_movement":$comm_etc[0];
        $website_access='steelmint';
        $sm_case = '';  $sm_case_1 = '';
// 		if($request['app_type']=='CM'){
//             $extra = json_decode(file_get_contents("https://www.coalmint.com/public/statsHeaderType.json"), true);
            
//             $website_access='coalmint';
//         }
//         else{
//             //echo config('constants.siteUrl')."public/statsHeaderType.json";
//             $extra = json_decode(file_get_contents(siteUrl."public/statsHeaderType.json"), true);				
//             $sm_case = " and (commodity<>'Coal' || (commodity='Coal' and subCommodity IN ('Met Coke', 'Coking Coal')) || (commodity='Coal' and subCommodity IN ('Non Coking Coal') and country='south africa')) ";
//             $sm_case_1 = "  and (commodity<>'Coal' || (commodity='Coal' and subCommodity IN ('Met Coke', 'Coking Coal'))) ";
//         }
        $extra = json_decode(file_get_contents(siteUrl."public/statsHeaderType.json"), true);				
        ///print_r($extra);
		$subCommodityGroupBy='subCommodity';
	    if($comm_etc[2]=='All' || $comm_etc[2]==''){
			$data["extra"] = $extra[strtolower($datatype)][$comm_etc[1]];
			$subCommodityGroupBy='commodity';
		}else
			$data["extra"] = $extra[strtolower($datatype)][$comm_etc[1]."-".$comm_etc[2]];
		
		if(isset($request['resourceType']) && $request['resourceType']=='app'){
			$sql = "SELECT DISTINCT `tradeType`,
			`commodity`,
			`subCommodity`,
			`country`,
			DATE_FORMAT(`dataAvailableFrom`, '%b-%Y') as dataAvailableFrom,
			DATE_FORMAT(`dataAvailableTo`, '%b-%Y') as dataAvailableTo,
			DATE_FORMAT(`lastUpdated`, '%d-%b-%Y') as lastUpdated,
			(select id from commo_region_ordering where commodity = tbl_historical_landing_bm.commodity and subCommodity = tbl_historical_landing_bm.subCommodity and subSubCommodity = tbl_historical_landing_bm.subSubCommodity and country = tbl_historical_landing_bm.country) as forderby,
			(SELECT c.`country_code` FROM `tbl_country` c WHERE c.`country` = tbl_historical_landing_bm.country limit 1) as country_flag
			FROM `tbl_historical_landing_bm` WHERE `section` = 'statistics' ".($comm_etc[2] != "All"?"AND `subCommodity`='{$comm_etc[2]}' AND `commodity` = '{$comm_etc[1]}' ":" AND `commodity` = '{$comm_etc[1]}'")." " .($request["regions"] !=""?"AND `country` IN ('".$request["regions"]."')":""). "  $sm_case
			GROUP BY `tradeType`,`$subCommodityGroupBy`,
			`country` ORDER BY forderby LIMIT " . $page_first_result . "," . $results_per_page;
			 if($request['debug']=='Y')       
                print_r($sql);
			$sql = mysql_query($sql);
			while($row = mysql_fetch_array($sql,MYSQL_ASSOC)){
				 $data["result"][] = $row;				 
			}
			$status = array(
				   'code' => $status,
				   'message' => 'success' 
			);
			   $responce = array(
				 'data' => $data,
				 'status' => $status
			);
			return $responce;
		}else{
			$sql = "SELECT DISTINCT `tradeType`,
			`commodity`,
			`subCommodity`,
			`country`,
			DATE_FORMAT(`dataAvailableFrom`, '%b-%Y') as dataAvailableFrom,
			DATE_FORMAT(`dataAvailableTo`, '%b-%Y') as dataAvailableTo,
			DATE_FORMAT(`lastUpdated`, '%d-%b-%Y') as lastUpdated,
			(select id from commo_region_ordering where commodity = tbl_historical_landing_bm.commodity and subCommodity = tbl_historical_landing_bm.subCommodity and subSubCommodity = tbl_historical_landing_bm.subSubCommodity and country = tbl_historical_landing_bm.country) as forderby,
			(SELECT c.`country_code` FROM `tbl_country` c WHERE c.`country` = tbl_historical_landing_bm.country limit 1) as country_flag
			FROM `tbl_historical_landing_bm` WHERE `section` = 'statistics' ".($comm_etc[2] != "All"?"AND `tradeType` = '{$datatype}' AND `subCommodity`='{$comm_etc[2]}' AND `commodity` = '{$comm_etc[1]}' ":" AND `tradeType` = '{$datatype}' AND `commodity` = '{$comm_etc[1]}'")." " .($request["regions"] !=""?"AND `country` IN ('".$request["regions"]."')":""). " $sm_case
			GROUP BY `tradeType`,`$subCommodityGroupBy`,
			`country` ORDER BY forderby LIMIT " . $page_first_result . "," . $results_per_page;
			 if($request['debug']=='Y')       
                print_r($sql);

			$sql = mysql_query($sql);
			while($row = mysql_fetch_array($sql,MYSQL_ASSOC)){
				 $data["result"][] = $row;				 
			 }
		}
		
		 
        
		 $sql_2 = mysql_query("SELECT DISTINCT `tradeType`,
			`commodity`,
			`subCommodity`,
			`country`,
			`dataAvailableFrom`,
			`dataAvailableTo`,
			`lastUpdated`,
        	(select id from commo_region_ordering where commodity = tbl_historical_landing_bm.commodity and subCommodity = tbl_historical_landing_bm.subCommodity and subSubCommodity = tbl_historical_landing_bm.subSubCommodity and country = tbl_historical_landing_bm.country) as forderby
        	FROM `tbl_historical_landing_bm` WHERE `section` = 'statistics' ".($comm_etc[2] != "All"?"AND `tradeType` = '{$datatype}' AND `subCommodity`='{$comm_etc[2]}' AND `commodity` = '{$comm_etc[1]}' ":" AND `tradeType` = '{$datatype}' AND `commodity` = '{$comm_etc[1]}'")." " .($request["regions"] !=""?"AND `country` IN ('".$request["regions"]."')":""). " 
        	 $sm_case_1
        	GROUP BY `tradeType`,`$subCommodityGroupBy`,
			`country` ORDER BY forderby");
		
		 $counts = mysql_num_rows($sql_2);
		 $data['pages'] = ceil($counts/$results_per_page);
		 return $data;
    }
	
	public static function actionsPostInfographicsPublish($postID){
		//include_once "/home/steelmin/public_html/inc/config1.php"; 
		//reset accessibleToPreLogin as N for all rows
		mysql_query("
			update 	tbl_stats_infographics 
			set		accessibleToPreLogin = 'N'
		");
		
		//set accessibleToPreLogin as N for top 2 infographics to be accessible by pre-login users
		mysql_query("
			UPDATE tbl_stats_infographics
			SET accessibleToPreLogin = 'Y'
			WHERE 1
			ORDER BY id desc
			LIMIT 4;
		");
			file_get_contents("https://aws.steelmint.com/update_news_extra_details.php?news_id=" . $postID . "&t=infographics");
	}
	public static function actionsPostIntelPublish($postID){
        //include_once "/home/steelmin/public_html/inc/config1.php"; 
		/*
		//YKV_23Jun2023 Code to set cron for notification starts
		$sql1 = "select * from intel where post_id = $postID";
		$res1=mysql_query($sql1);
		while($row=mysql_fetch_assoc($res1)){
			if($row['isCronSet'] != 'y'){
				$cronTime = strtotime($row['datePublished']. '+30 minutes');
				$hours = date('H',$cronTime);
				$mdays = date('d',$cronTime);
				$minutes = date('i',$cronTime);
				$months = date('m',$cronTime);
				$wdays = date('w',$cronTime);
				if($row['for_smgroup_company'] == 'steelmint.com,coalmint.com' || $row['for_smgroup_company'] == 'coalmint.com,steelmint.com'){
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php");
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php?forCompany=CM");
				}
				elseif($row['for_smgroup_company'] == 'coalmint.com'){
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php?forCompany=CM");
				}
				else{
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php");
				}
			}
		}
		
		mysql_query("UPDATE intel SET isCronSet = 'y' where post_id = $postID");
		//YKV_23Jun2023 Code to set cron for notification ends
		*/
		mysql_query("UPDATE intel AS to_update
		INNER JOIN tbl_state_city AS update_from
		ON to_update.cityID = update_from.ID
		AND to_update.continentID = 0
		SET to_update.continentID = update_from.continentID,
			to_update.regionID = update_from.country_id
		");		
		
		//file_get_contents("https://www.steelmint.com/steeladmin/wp_post_entry_in_sm_db.php?news_id=" . $postID . "&t=intel");
		file_get_contents("https://aws.steelmint.com/update_news_extra_details.php?news_id=" . $postID . "&t=intel");
		file_get_contents("https://www.steelmint.com/registrationAJAX.php?updateIntelHREF=1");
		mysql_query("UPDATE tbl_intel_insight_hashmap AS to_update
		INNER JOIN intel AS update_from
		ON 	to_update.post_id = $postID
		AND update_from.post_id = $postID		
		SET to_update.continentID = update_from.continentID,
			to_update.regionID = update_from.regionId,
			to_update.author_name = update_from.author_id,
			to_update.indexing = update_from.indexing,
			to_update.for_smgroup_company = update_from.for_smgroup_company");
		
		
		updateJSONforAPPExplorePage("intel",$postID);
		//include_once "/home/steelmin/public_html/inc/desconfig.php"; 


		
//		\ApiQuery::addPostToSiteMap($postID, 'intel');
		
		//update showInCommodityWise = 1 in tbl_news_post
		\ApiQuery::update_indexing_column($postID, 'intel');
		
		//remove the redis key which is used on new home page of steelmint.
		include_once "/home/steelmin/public_html/redisFn.php";
		removeKeyValueFromRedis("new_web_home_intelinsight_prelogin");
	}	
	
	
	
	public static function actionsPostInsightPublish($postID, $locationID){
		//$ln = $locationID;
		//include_once "/home/steelmin/public_html/inc/config1.php";
		//file_get_contents("https://www.steelmint.com/steeladmin/wp_post_entry_in_sm_db.php?news_id=" . $postID . "&t=insight");
		file_get_contents("https://aws.steelmint.com/update_news_extra_details.php?news_id=" . $postID . "&t=insight");
		file_get_contents("https://www.steelmint.com/registrationAJAX.php?scheduleEmail_new=Y&post_id=" . $postID);
	//	file_get_contents("https://www.steelmint.com/eccode/tag_data.php?post_id=" . $postID);
		/*
		//YKV_23Jun2023 Code to set cron for email & notification starts
		$sql1 = "select * from tbl_news_post where post_id = $postID";
		$res1=mysql_query($sql1);
		while($row=mysql_fetch_assoc($res1)){
			if($row['isCronSet'] != 'y'){
				$cronTime = strtotime(($row['post_date'].' '. $row['post_time']). '+30 minutes');
				$hours = date('H',$cronTime);
				$mdays = date('d',$cronTime);
				$minutes = date('i',$cronTime);
				$months = date('m',$cronTime);
				$wdays = date('w',$cronTime);
				if($row['for_smgroup_company'] == 'steelmint.com,coalmint.com' || $row['for_smgroup_company'] == 'coalmint.com,steelmint.com'){
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php");
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php?forCompany=CM");
				}
				elseif($row['for_smgroup_company'] == 'coalmint.com'){
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php?forCompany=CM");
				}
				else{
					file_get_contents("https://www.steelmint.com/cron_job.php?hours=$hours&mdays=$mdays&minutes=$minutes&months=$months&wdays=$wdays&cronURL=https://www.steelmint.com/nf.php");
				}
			}
		}
		mysql_query("UPDATE tbl_news_post SET isCronSet = 'y' where post_id = $postID");
		//YKV_23Jun2023 Code to set cron for email & notification ends
		*/
		include_once "/home/steelmin/public_html/hf.php";
		updateJSONforAPPExplorePage("insight",$postID);


/* 		if( $ln != 0 ){
			$country_id = qryToCommaSepString("select country_id from tbl_state_city where id = " . $ln);
			
			if( $country_id == 113 )
				$continentID = 113;
			elseif( $country_id == 49 )
				$continentID = 49;
			else
				$continentID = qryToCommaSepString("select parentID from tbl_region_commodity_master where itemType = 'region' and id = $country_id");
			
			$sql = "
				update tbl_news_post
				set continentID = $continentID
				where post_id = $postID
			";
			$result = mysql_query($sql) or die ('Error: ' . mysql_error());
		} */
		
		mysql_query("UPDATE tbl_news_post AS to_update
		INNER JOIN tbl_state_city AS update_from
		ON to_update.cityID = update_from.ID
		AND to_update.continentID = 0
		SET to_update.continentID = update_from.continentID,
			to_update.regionId = update_from.country_id
		");
		//get data from  tbl_news_post and update tbl_intel_insight_hashmap 
		mysql_query("UPDATE tbl_intel_insight_hashmap AS to_update
		INNER JOIN tbl_news_post AS update_from
		ON 	to_update.post_id = $postID
		AND update_from.post_id = $postID		
		SET to_update.continentID = update_from.continentID,
			to_update.regionID = update_from.regionId,
			to_update.author_name = update_from.author_id,
			to_update.indexing = update_from.indexing,
			to_update.for_smgroup_company = update_from.for_smgroup_company");
			
		
		//update showInCommodityWise = 1 in tbl_news_post
		\ApiQuery::update_indexing_column($postID);

		//update showInCommodityWise = 1 in tbl_news_post
		\ApiQuery::update_all_sub_commodities();
		
		//update showInRegionWise = 1 in tbl_news_post
		\ApiQuery::update_all_sub_region();

		//closeTheInsightPublishTask($postID);
//		\ApiQuery::addPostToSiteMap($postID);
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		
		//remove the redis key which is used on new home page of steelmint.
		include_once "/home/steelmin/public_html/redisFn.php";
		removeKeyValueFromRedis("new_web_home_intelinsight_prelogin");
		
	}

	public static function update_indexing_column($postID, $tbl='tbl_news_post'){
		if($tbl=='tbl_news_post'){
			$sql1="
				SELECT 	id,
				post_title,
				post_content,
				(select itemName from tbl_region_commodity_master as cm where tbl_news_post.commodityId=cm.id) as commodity,
				(select itemName from tbl_region_commodity_master as cm where tbl_news_post.subCommodityId=cm.id) as subCommodity,
				(select itemName from tbl_region_commodity_master as cm where tbl_news_post.subSubCommodityId=cm.id) as subSubCommodity,
				(select itemName from tbl_region_commodity_master as cm where tbl_news_post.continentID=cm.id) as continentname,
				(select country from tbl_country as cm where tbl_news_post.regionId=cm.id) as countryname
				FROM 	tbl_news_post 
				where 	post_id = $postID
			";
		}else{
			$sql1="
				SELECT 	itemId as id,
				title as post_title,
				description as post_content,
				(select itemName from tbl_region_commodity_master as cm where intel.commodityId=cm.id) as commodity,
				(select itemName from tbl_region_commodity_master as cm where intel.subCommodityId=cm.id) as subCommodity,
				(select itemName from tbl_region_commodity_master as cm where intel.subSubCommodityId=cm.id) as subSubCommodity,
				(select itemName from tbl_region_commodity_master as cm where intel.continentID=cm.id) as continentname,
				(select country from tbl_country as cm where intel.regionId=cm.id) as countryname
				FROM 	intel 
				where 	post_id = $postID
			";
		}
			$res1=mysql_query($sql1);

			while($row=mysql_fetch_assoc($res1))
			{
				$sound=" ";
				$sound = $row['continentname'] . ' ' . $row['countryname'] . ' ' . $row['subSubCommodity'] . ' ' . $row['subCommodity'] . ' ' . $row['commodity'] . ' ' . $row['post_title']  . ' ' . $row['post_content'] ;
				$id=$row['id'];
				$sound = str_replace(array(' ', '.'), '-', $sound); // Replaces all spaces with hyphens.
				$sound  = strip_tags(html_entity_decode($sound, ENT_QUOTES));
				$sound =  preg_replace('/[^A-Za-z0-9\-]/', '', $sound); // Removes special chars.			
				//$sound  = strip_tags(html_entity_decode($sound, ENT_QUOTES));
				$sound = str_replace('-', ' ', $sound); // Replaces all spaces with hyphens.

				if($tbl=='tbl_news_post')
					$sql2="UPDATE `tbl_news_post` SET indexing='$sound' WHERE id=$id";
				else
					$sql2="UPDATE `intel` SET indexing='$sound' WHERE itemId=$id";
				$res2=mysql_query($sql2);
			}		
	}

	public static function update_all_sub_region(){
		/* $sql = "
			SELECT `continentID`,
				   group_concat(`post_id`
								ORDER BY `post_id` DESC) AS ids
			FROM tbl_news_post
			WHERE 1
			  AND for_smgroup_company LIKE '%steelmint%'
			  AND continentID <> 0
			GROUP BY continentID
			ORDER BY post_id DESC
		"; */
		
		$sql = "
			SELECT (select country_id from tbl_state_city where id = tbl_news_post.cityID) as cntryID,
				   group_concat(`post_id`
								ORDER BY `post_date` DESC, post_time DESC) AS ids
			FROM tbl_news_post
			WHERE 1
			  AND for_smgroup_company LIKE '%steelmint%'
			  AND cityID <> 0
			GROUP BY cntryID
			ORDER BY post_id DESC
		";
		
		$res = mysql_query($sql) or die(mysql_error().$sql);
		$_post_ids = '';
		while($row = mysql_fetch_assoc($res,MYSQL_ASSOC))
		{
			$resArr = explode(',', $row['ids']);
			$input_array = array_chunk($resArr, 20);
			if(isset($input_array[0])){
				if($_post_ids != '')
					$_post_ids.=',';
				
				$_post_ids.=implode(',',$input_array[0]); 
			}
		}
		mysql_query("
			update tbl_news_post 
			set showInRegionWise = 0
			where 1
		") or die(mysql_error());	

		mysql_query("
			update tbl_news_post 
			set showInRegionWise = 1
			where post_id in ($_post_ids)
		") or die(mysql_error());	
	}

	public static function update_all_sub_commodities(){
		$sql = "
			
			SELECT 
					case
						when `subSubCommodityId` = 0 then subCommodityId
						else subSubCommodityId
					end as ssc,
				   group_concat(`post_id`
								ORDER BY `post_date` DESC, post_time DESC) AS ids
			FROM tbl_news_post
			WHERE 1
			  AND for_smgroup_company LIKE '%steelmint%'
			GROUP BY ssc
			ORDER BY post_id DESC
		
		";
		$res = mysql_query($sql) or die(mysql_error().$sql);
		$_post_ids = '';
		while($row = mysql_fetch_assoc($res,MYSQL_ASSOC))
		{
			$resArr = explode(',', $row['ids']);
			$input_array = array_chunk($resArr, 20);
			if(isset($input_array[0])){
				if($_post_ids != '')
					$_post_ids.=',';
				$_post_ids.=implode(',',$input_array[0]); 
			}
		}
		mysql_query("
			update tbl_news_post 
			set showInCommodityWise = 0
			where 1
		") or die(mysql_error());	

		mysql_query("
			update tbl_news_post 
			set showInCommodityWise = 1
			where post_id in ($_post_ids)
		") or die(mysql_error());	
	}
	
	public static function closeTheInsightPublishTask($postID){
		
		if($_COOKIE['news_task_id'] != '' && $_COOKIE['userId']!=''){
			$data = array('message' => $post_title, 'post_id' => $postID);
			$cookie_string="";
			foreach( $_COOKIE as $key => $value ) {
				$cookie_string .= "$key=$value;";
			};
			$header = array("Cookie: " . $cookie_string);
			$ch = curl_init();
			curl_setopt( $ch,CURLOPT_URL, "https://www.steelmint.com/steeladmin/operations/master_tables/task_management/news_publish.php");
			curl_setopt( $ch,CURLOPT_POST, true );
			curl_setopt($ch, CURLOPT_HTTPHEADER,$header );    
			curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
			curl_setopt( $ch,CURLOPT_POSTFIELDS, http_build_query($data));
			$result = curl_exec($ch );
			curl_close( $ch );
			ob_flush();

			setcookie("news_task_id", "", time()-3600);	
			setcookie("news_task_id", "", time()-3600, '/');
			echo '
				<script>
				document.cookie = "news_task_id=; path=/";    
				</script>';
		}	
	}
	   
	  public static function addPostToSiteMap($post_id, $section="insight") {
		  
		if($section=='insight')
			$postData  =   get_news_by_id($post_id);
		elseif($section=='infographics'){//infographics
			//$postData  =   get_news_by_id($post_id);
			$sql = "SELECT n.post_title, 'steelmint.com' as for_smgroup_company,  created_at, concat('".BASEURL."statistics/infographic/detail/',post_id) as full_url FROM `tbl_stats_infographics` n";
	
			$sql .= " WHERE n.`post_id` = " . (int)$post_id;	
			$result = mysql_query($sql) or die ('Error: ' . mysql_error());
			$postData = mysql_fetch_assoc($result);			
		}elseif($section=='intel'){//infographics
			//$postData  =   get_news_by_id($post_id);
			$sql = "SELECT post_id, replace(url_screen_name, '/insights/', '/intel/') as full_url, datePublished as created_at, title as post_title, 'steelmint.com' as for_smgroup_company, year(datePublished) as `yr`
						FROM `intel` n";
	
			$sql .= " WHERE n.`post_id` = " . (int)$post_id;	
			$result = mysql_query($sql) or die ('Error: ' . mysql_error());
			$postData = mysql_fetch_assoc($result);			
		}
		
		$title = $postData['post_title'];		
		$for_smgroup_company = explode(",",$postData['for_smgroup_company']);
		$post_modified = $postData['created_at'];
		$_post_date_arr = explode("-", $post_modified);//YYYY-MM-DD HH:MM:SS
		$post_name  = $postData['post_title'];///url title exclude ID
		$myDateTime = new DateTime($post_modified, new DateTimeZone('GMT'));
		$myDateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));
		//$post_modified  =  $myDateTime->format('Y-m-dTH:i:sP');
		$post_modified  =  $myDateTime->format('Y-m-d');
		$post_modified  =  $post_modified .'T'. $myDateTime->format('H:i:sP');
		
		$yr = $_post_date_arr[0];
		///
		//$key1_values = get_post_meta($post_id , 'news_for_website', true);
		foreach($for_smgroup_company as $webs){
			$_path = "/home/steelmin/public_html/";
			/*$_loc = "https://www.steelmint.com/news/";			
				if($webs=='coalmint.com'){
					$_path = "/home/steelmin/public_html/coalmint/";
					$_loc = "https://www.coalmint.com/news/";
				}*/
				$_loc =$postData['full_url'];
				if($webs=='coalmint.com'){
					$_path = "/home/steelmin/public_html/coalmint/";
					//$_loc = "https://www.coalmint.com/news/";
					$_loc = str_replace('steelmint.com', $webs, $_loc);
				}
			$file = $_path . "news/XMLs/".$yr.".xml";			
			if (!file_exists($file)) {
				$fp = fopen($file, 'w');
				$sitemap_header = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="https://www.google.com/schemas/sitemap-news/0.9"></urlset>';
				fwrite($fp, $sitemap_header);
				fclose($fp);
			}			
			$fp = fopen($file, 'r') or die("Unable to open file!");			$content = fread($fp,filesize($file));
			//$content = str_replace('</urlset>','', $content);			
			$_new_sitemap='';			
			if (strpos($content, 'id="'.$post_id.'"') !== false) {
			   $replacement ='<loc>'.$_loc .'</loc>'.
					  '<lastmod>'. $post_modified .'</lastmod>'.
					  '<changefreq>monthly</changefreq>'.
					  '<priority>0.8</priority>';
				
				$content = replace_between($content, '<url id="'.$post_id.'">', '</url>', $replacement);		
			} else  {///new
				$_new_sitemap = '<url id="'.$post_id.'">'.
					  '<loc>'.$_loc.'</loc>'.
					  '<lastmod>'. $post_modified .'</lastmod>'.
					  '<changefreq>monthly</changefreq>'.
					  '<priority>0.8</priority>'.
					'</url>';				
				$sitemap_header = '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9" xmlns:news="https://www.google.com/schemas/sitemap-news/0.9">';		
				$content = str_replace($sitemap_header, $sitemap_header.$_new_sitemap, $content);
			}
			/*$sitemap = $content . $_new_sitemap;*/
			$sitemap = $content;
			/// $sitemap .= '</urlset>';
			$fp = fopen($file, 'w');
			fwrite($fp, $sitemap);
			fclose($fp); 
		}
	}


	public static function getIntelRowSet($memid=0,$resourceType="app", $type='', $filters=array(), $pageType='post', $limits=5, $offset=0, $appType='SM'){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		////include_once "/home/steelmin/public_html/inc/config1.php"; 
        $result=array(); 
        /*if($resourceType=="web"){       
           $sql = "SELECT `itemID`, (select itemName from tbl_region_commodity_master as cm where intel.subCommodityId=cm.id and itemType='commodity') as commodityName, `title`, `description`, `videoUrl`, `imageUrl`, `videoUrl`, `datePublished`, `type`, `isAd`, `ad_image`, `ad_action`, `url_screen_name`, `created_at` FROM `intel` WHERE itemId>0 ";*/
        //} else {
			/*if($pageType == "pre" || $pageType == "pre_1")	
			   $no_ad = ' AND isAd="n" ';
			else
			   $no_ad = ""; */
		
    
            if($offset == 0){ //1584 = itemId of tata AD. In page 1 , always show tata ad in 5th position
				if(!isset($filters['intelInsideInsight']) && $resourceType != 'web'){
					$no_ad .= ' and ( isAd="n" || (isAd="y" and itemID in (1817))) ';			
				} else
					$no_ad = ' AND isAd="n" ';	
		    } else
		        $no_ad = ' AND isAd="n" ';	

			
		   
		   $dt_from = date("Y-m-d 23:59:59");
           $dt_to = date('Y-m-d 00:00:00', strtotime('-7 days'));		   
		   
           $sql = "SELECT  f_timetoread, `itemID`,
                            (select itemName from tbl_region_commodity_master as cm where intel.subCommodityId=cm.id and itemType='commodity') as commodityName,
                            (select itemName from tbl_region_commodity_master as cm where intel.commodityId=cm.id and itemType='commodity') as cn,
                            (select itemName from tbl_region_commodity_master as cm where intel.subSubCommodityId=cm.id and itemType='commodity') as cn1,
							(select itemName from tbl_region_commodity_master as cm where intel.regionID=cm.id and itemType='region') as regionName,
                            `title`, `description`, `videoUrl`, `imageUrl`, `videoUrl`, `datePublished`, `type`, `isAd`, `ad_image`, `ad_action`, `url_screen_name`, `created_at`,most_read as noOfReads, for_smgroup_company 
							,author_name, author_id, author as author_email, f_excerpt, f_tags
							FROM `intel`  WHERE itemId>0 $no_ad  ";  
  		   
		   
		   /* removed 7 days restriction  using $filters['show_all'] 
		   * it should be Y if we have to remoce restriction
		   */
		   if(!isset($filters['post_id']) && !isset($filters['searchTerms']) && (!isset($filters['show_all']) && $filters['show_all']!='Y') && !isset($filters['featuredTab']))
			$sql .= "	AND (`datePublished` >= '$dt_to' AND `datePublished` <= '$dt_from') ";				
       // }   
        $source =='';
		/* echo "<pre>";
		print_r($filters); */
		if(isset($filters['source'])) {//source
			$source = $filters['source'];
			switch($source){				
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark':
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
					/* $bookMarkedIds = qryToCommaSepString("select lead_id from tbl_bookmark as b where  user_id=$memid and section='intel' and appType ='$appType' ");
					if($bookMarkedIds)
						$filter['itemID'] = explode(',', $bookMarkedIds);
					else
						$filter['itemID'] = 0; */
					$common = new Common();
					$bookMarkedIds = $common->getUserBookmarksV2019($resourceType, $memid, $section='intel', $status='', $event_id=0);
					if(count($bookMarkedIds)>0)
						$filters['itemID'] = explode(',', $bookMarkedIds);
					else
						$filters['itemID'] = 0;
				break;
				case 'portfolio':
                   /*  $common = new Common();
					$temp = $common->getUserPortfolioV2019($memid, 'news', $appType);		
					print_r($temp); */
					//and appType='".$appType."' 
					$sqlTC = "select regionId, commodityID from tbl_user_portfolio where user_id=".$memid." and type='intel_insight' order by id desc limit 1"; 
					$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
					$temp = mysql_fetch_array($rsTC,MYSQL_ASSOC);					
					if($temp['commodityID']){
						$commodityIDs = $temp['commodityID'];
						$filters['commodityID'] = explode(',',$commodityIDs);
					}
					if($temp['regionId']){
						$regionIDs = $temp['regionId'];
						$filters['regionID'] = explode(',',$regionIDs);
					}
					if(empty($filters['commodityID']) && empty($filters['regionID'])){
						return $result;
					}
					//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
			}
		}
		
		if( isset($filters['sliderID']) ){						
			if($filters['sliderID']!=''){
				$common = new Common();				
				$sliderRes = $common->getSliderDetails($filters['sliderID']);
				
				if(empty($sliderRes)){								
					$filters['commodityID'] = array(); 
					$filters['regionID'] = array();
				}else{
					if($sliderRes['commodityID'])
						$filters['commodityID'] = array($sliderRes['commodityID']); 
					if($sliderRes['regionID'])
						$filters['regionID'] = array($sliderRes['regionID']); 
				}				
			}else{							
				$filters['commodityID'] = array(); 
				$filters['regionID'] = array();								
			}
		}
		
		if(isset($filters['trendingTags']) && !empty($filters['trendingTags'])) {			
			//get trendingTags and pass as like in table intel
			$sql .= " AND FIND_IN_SET({$filters['trendingTags']},`trending_tag`) > 0 ";
		}
		if(isset($filters['commodityID'])) {
			$sql .= " AND (";
			$sql .= " commodityID In ( " .  implode(',',$filters['commodityID']) .  ")";	
			$sql .= " OR subCommodityID In ( " .  implode(',',$filters['commodityID']) .  ")";	
			$sql .= " OR subSubCommodityID In ( " .  implode(',',$filters['commodityID']) .  ")";	
			$sql .= ")";
		}
		if(isset($filters['searchTerms']) && !empty($filters['searchTerms'])) {
			$cd = date("Y-m-d");
			$ct = date("H:i:s");
			mysql_query("
				insert into tbl_searches 
				values (
				'',
				'$cd',
				'$ct',
				$memid,
				'intel',
				'" . htmlspecialchars($filters['searchTerms'], ENT_QUOTES) . "',
				'$resourceType'
				)"
			);
			
			$sql .= " having (";

			$implode = array();

			$words = explode(' ', trim(preg_replace('/\s+/', ' ', $filters['searchTerms'])));
			$words = str_replace(array("intel","intels"), "", $words);
			foreach ($words as $word) {
				//if( $memid == 116707 ){
					$implode[] = '(
						title REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
						commodityName REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 	
						description REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
						cn REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 	
						cn1 REGEXP "[[:<:]]' . $word . '[[:>:]]"
					)   ';
				/* } else {
					$implode[] = " (title like '%$word%' OR commodityName  like '%$word%' OR  description like '%$word%' OR cn  like '%$word%' OR cn1  like '%$word%')   ";
				} */
			}

			if ($implode) {
				$sql .= " " . implode(" AND ", $implode) . "";
			}

			$sql .= ")";
		}   		
		
		
 		// following code commented as we dont maintain region in intel section. will uncomments it once v start maintining the same
		if(isset($filters['regionID'])) {
			if(is_array($filters['regionID'])){
				$sql .= " AND (`continentID` IN (";
				$sql .= implode(", ", $filters['regionID']);
				$sql .= ") OR regionID IN (".implode(", ", $filters['regionID']).") ) ";
			}else{
				$sql .= " AND (";
				$sql .= " continentID = " .  implode(',',$filters['regionID']);
				$sql .= " OR  regionID = " .  implode(',',$filters['regionID']);
				$sql .=  ")";
			}
		}
		if(isset($filters['post_id'])) {
			if(is_array($filters['post_id']))
				$sql .= " AND (`post_id` IN (" . implode(',',$filters['post_id']) .") OR itemID IN (" . implode(',',$filters['post_id']) .") )"; 
			else{
				$pid = (int)$filters['post_id'];
				$sql .= " AND (`post_id` = $pid OR itemID = $pid)  ";
			}	
		}
		if(isset($filters['itemID']) && !isset($filters['intelInsideInsight'])) {
			if(is_array($filters['itemID']))
				$sql .= " AND `itemId` IN (" . implode(',',$filters['itemID']) .")"; 
			else
				$sql .= " AND `itemId` = " . (int)$filters['itemID'];
		}
		if(isset($filters['not_in']) && !isset($filters['intelInsideInsight'])) {
			if(is_array($filters['not_in']))
				$sql .= " AND `itemId` NOT IN (" . implode(',',$filters['not_in']) .")"; 
			else
				$sql .= " AND `itemId` <> " . (int)$filters['not_in'];
		}
		
		$sidebar_tab='';
		$dtFrom='';
		if(isset($filters['featuredTab']) && !empty($filters['featuredTab'])){
			$sidebar_tab = $filters['featuredTab'];			
			
			switch(strtolower($sidebar_tab)){
					case 'most-read':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -15 days'));
						$filters['orderBy'] = " most_read ";
					break;
					case 'top':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -7 days'));
						$filters['orderBy'] = " most_read ";
					break;
					case 'editorial':
						//$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -2 days'));
						$sql .= " AND author_id=36 ";
						$filters['orderBy'] = " datePublished ";						
					break;
			}
			if($dtFrom!='')
					$sql .= " AND DATE(`datePublished`) >= '$dtFrom' ";	
		}
		else{
			if(isset($filters['timeLine']) || isset($filters['timeline'])) {
				$dtFrom = $GLOBALS['currDate'];
				if( isset($filters['timeLine']) )//coming in android
					$timeLine = $filters['timeLine'];
				if( isset($filters['timeline']) )//coming in ios
					$timeLine = $filters['timeline'];
				switch(strtolower($timeLine)){
					case '1w':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -7 days'));
						$mapLimit = "50";
						//$sql .= " AND DATE(n.`post_date`) >= '$dtFrom'";
					break;
					case '2w':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -14 days'));
						$mapLimit = "50";
					break;
					case '2d':
						//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 2 DAY)";
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -2 days'));
						$mapLimit = "30";
					break;
				}
				
				$sql .= " AND DATE(`datePublished`) >= '$dtFrom'";
			}
			
			if(isset($filters['fromDate']) && $filters['fromDate'] != ''){
				$dt = date('Y-m-d', strtotime($filters['fromDate']));
				$sql .= " AND DATE(`datePublished`) >= '$dt'";
			}
			
			if(isset($filters['toDate']) && $filters['toDate'] != '' && $filter['toDate'] != 'tillDate'){
				$dt =   date('Y-m-d', strtotime($filters['toDate']));
				$sql .= " AND DATE(`datePublished`) <= '$dt'";
			}
		}
		/* if(isset($filters['intelInsideInsight']) || $resourceType=='web') {
			$sql .= " AND `isAd` = 'n' ";
		} */
		//$sql .= " AND datePublished < '".$GLOBALS['currDate']."'  ";
		$user = new User($memid, $appType);
		$isAccessible =  $user->isAccessible($resourceType, $section='Intel','','','',$filters['selected_market']);
		
		if($isAccessible==-1 && !isset($filters['searchTerms']) && !isset($filters['featuredTab'])){//post
		    /*if(!empty(Session::get('sectionFromDate'))){			
			    $sectionFromDate = Session::get('sectionFromDate');
		    	$sql .= " AND datePublished >= '$sectionFromDate'";			
		    }*/
		    if(!empty(Session::get($filters['selected_market'])['sectionFromDate'])){			
			    $sectionFromDate = Session::get($filters['selected_market'])['sectionFromDate'];
		    	$sql .= " AND datePublished >= '$sectionFromDate'";			
		    }else{
				$sql .= " AND datePublished = '2001-01-01'";	
			}
		}
		
		if(strtolower($source) == 'newsletter'){
			$sql .= " AND datePublished like '".date_yesterday()."%'";
		}
		
		//echo "at:" . $appType;
		$web_domain = $appType=='CM' ? "coalmint.com" : "steelmint.com";
		
		/*if(strtolower($filters['sourceNew']) != 'newsletter'){
			$sql .= " and `for_smgroup_company` like '%";
		
			if(strpos($web_domain, "coalmint.com") !== false) {
				$sql .= "coalmint.com";
			} else {
				 $sql .= "steelmint.com";
			}
			$sql .= "%' ";
		}
		*/
		//$sql .= " group by itemID ";	
		//print_r($filters['orderBy']);
		if(isset($filters['orderBy'])) {
			$sql .= " order BY {$filters['orderBy']} desc";
		} else{
			//$sql .= " order BY itemId desc";
			$sql .= " 
				ORDER BY 
				case
					when itemId  in (1817) then 1
					else 99
				end, itemId	desc			
			";
		}
		if($source=='home')
			$limit = DEFAULT_LIMIT_INTEL;
		elseif(isset($filters['featuredTab']) && !empty($filters['featuredTab']))
			$limit = 5;
		elseif(isset($filters['API_Key']) && $filters['API_Key']=='1dP9kOjmxZDt1')
			$limit = 100;
		else
			$limit = DEFAULT_LIMIT_INTEL;
		if($pageType == "pre" && !isset($filters["intelInsideInsight"])){
			//$filter["intelInsideInsight"] => this key is passed when API is called from intel tab which is inside the insights section
		    $limit = $limits;
		}
		
		if( $limit < 0 )
			$limit = 1;
		
		$tc = 0;
		if(isset($filters['searchTerms']) && !empty($filters['searchTerms'])) {		
			$a = mysql_query($sql);
			$tc = mysql_num_rows($a);
		}
		if(strtolower($source) == 'newsletter')
			$sql .= " LIMIT 0, 600";
		elseif($limit != '')
			 $sql .= " LIMIT $offset,$limit";
			//echo "sql:" . $sql;
		
		
		
		if((isset($filters['debug']) && $filters['debug'] == 1)) {
            echo "<br /><br /><pre>final sql intel:", $sql . ' -- ' . $offset . ' -- ' . $limit . ' -- ' . $memid . ' -- ' . $source;
			echo "<pre>";
			print_r($filters)	;
        } 
		/* if( 56350 == $memid ){
			echo "<br /><br /><pre>final sql:", $sql;
			echo "<pre>";
			print_r($filters)	;
		} */
			
            $query = mysql_query($sql);
			$result["Intels"]=array();
			$posOf5thItem = -1;
			$posOf7thItem = -1;
			$cnt = 0;
            while($row = mysql_fetch_assoc($query)){				
				$row["noOfReads"] = (int)$row["noOfReads"];
				$row['timeToRead'] = $row['f_timetoread'];
				$row['regionName'] = is_null($row['regionName'])?'Others':$row['regionName'];
                $time_ago = strtotime($row["created_at"]);
                $cur_time   = time();
                $time_elapsed   = $cur_time - $time_ago;
                $seconds    = $time_elapsed ;
                $minutes    = round($time_elapsed / 60 );
                $hours      = round($time_elapsed / 3600);
                $days       = round($time_elapsed / 86400 );
                $weeks      = round($time_elapsed / 604800);
                $months     = round($time_elapsed / 2600640 );
                $years      = round($time_elapsed / 31207680 );
                // Seconds
                if($seconds <= 60){
                    $row["added_at"] = "just now";
                }
                //Minutes
                else if($minutes <=60){
                    if($minutes==1){
                        $row["added_at"] = "one minute ago";
                    }
                    else{
                        $row["added_at"] =  "$minutes minutes ago";
                    }
                }
                //Hours
                else if($hours <=24){
                    if($hours==1){
                        $row["added_at"] =  "an hour ago";
                    }else{
                        $row["added_at"] =  "$hours hrs ago";
                    }
                }
                //Days
                else if($days <= 7){
                    if($days==1){
                        $row["added_at"] =  "yesterday";
                    }else{
                        $row["added_at"] =  "$days days ago";
                    }
                }
                //Weeks
                else if($weeks <= 4.3){
                    if($weeks==1){
                        $row["added_at"] =  "a week ago";
                    }else{
                        $row["added_at"] =  "$weeks weeks ago";
                    }
                }
                //Months
                else if($months <=12){
                    if($months==1){
                        $row["added_at"] =  "a month ago";
                    }else{
                       $row["added_at"] =  "$months months ago";
                    }
                }
                //Years
                else{
                    if($years==1){
                        $row["added_at"] = "one year ago";
                    }else{
                        $row["added_at"] =  "$years years ago";
                    }
                }
                $row["itemID"] =  intval($row["itemID"]);
				/* if( $row["itemID"] == 1710 )
					$posOf5thItem = $cnt; */
				if( $row["itemID"] == 1817 )
					$posOf7thItem =  $cnt;
				
				
				$row["title"] = utf8_decode(stripslashes(html_entity_decode($row['title'] )));	
				///$hrf = BASEURL."intel/".url_title($row['title'].'-'.$row['itemID'],$separator = '-', $lowercase = true);
				$hrf = config('constants.siteUrl')."/intel/detail/".url_title($row['title'].'-'.$row['itemID'],$separator = '-', $lowercase = true);
				$row["href"]=$hrf;
				// showIntel => whether the user can view intel in the description page or not. 
				// $intelID = intelID user is tryign to view
				// case 1: user has exhausted his daily viewing limit. if $intelID lies in the set of intels which he has viewed today then showIntel = Y else showIntel = N		
				// case 2: user has NOT exhausted his daily viewing limit and that either he has viewed 0 intels today orviewed few intels. In either case showIntel = Y		
				if( isset($filters["showIntel"]) ){
					if( $filters["showIntel"] == 'Y' )
						$row["description"] = utf8_decode(stripslashes(html_entity_decode($row['description'])));
					else
						$row["description"] = "hidden";
				}else
					$row["description"] = utf8_decode(stripslashes(html_entity_decode($row['description'])));
				
                
                //replace all break points between ul tag in intel
                //get_string_between is defined in hf.php
                $subStr_old = get_string_between($row["description"], "<ul", "</ul>");
                $subStr_new = str_replace("<br />", "", $subStr_old);
                $row["description"] = str_replace($subStr_old, $subStr_new, $row["description"]);

                $subStr_old = get_string_between($row["description"], "<ol", "</ol>");
                $subStr_new = str_replace("<br />", "", $subStr_old);
                $row["description"] = str_replace($subStr_old, $subStr_new, $row["description"]);
				$row["description"] = str_replace("<p><p>", "", $row["description"]);
				$row["description"] = str_replace("</p></p>", "", $row["description"]);
				$row["description"] = str_replace("<p>", "", $row["description"]);
				$row["description"] = str_replace("</p>", "", $row["description"]);
				
				
				
				//$row["description"] = str_replace('</li><br />', '</li>', $row["description"]);
				
				
				/* if( 116707 == $memid )
					$row["description"] = "<ul style='list-style-type: square;'><li style='vertical-align: middle;font-size: 170%;line-height: 120%;'>point 1</li><li style='vertical-align: middle;font-size: 170%;line-height: 120%;'>point 2</li><li style='vertical-align: middle;font-size: 170%;line-height: 120%;'>point 3</li></ul>"; */
				
				//$row["ad_image"] = "https://www.steelmint.com/fotomine/api/public/fotomine/images/99-80/jamshedur-plant-2-99-80-5c1c8148453d9.jpg";
				//$row["ad_action"] = "open_screen";
				$row["postedDateTime"] = date('M d, Y H:i', strtotime($row['datePublished']));;
				//$row["url_screen_name"] = "www.steelmint.com/web_app.php?source=ironOre";
				unset($row["created_at"]);
				/*if($pageType == "pre"){
					$row["is_new"] = "Y";
				}else if($pageType == "pre_1"){
					$row["is_new"] = "Y";
				}else{
                    $row["is_new"] = "N";
				}*/
				//Commented by YKV to avoid img.steelmint.com broken image issue - 11 Feb'23
				//$row["imageUrl"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", $row["imageUrl"]);
				
				
                // Check if $row["imageUrl"] contains "wp-insights-sm.s3.ap-south-1.amazonaws.com"
                if (strpos($row["imageUrl"], "wp-insights-sm.s3.ap-south-1.amazonaws.com") !== false) {
                    $row["imageUrl"] = str_replace("wp-insights-sm.s3.ap-south-1.amazonaws.com", "d199amilqw5tyr.cloudfront.net", $row["imageUrl"]);
                }
                // Check if $row["imageUrl"] contains "https://www.steelmint.com/news"
                elseif (strpos($row["imageUrl"], "https://www.steelmint.com/news") !== false) {
                    $row["imageUrl"] = str_replace("https://www.steelmint.com/news", "https://www.steelmint.com/news", $row["imageUrl"]);
                }
                
                // Output the modified URL for verification
                //echo $row["imageUrl"];				
				
				
				//$row["imageUrl"] = str_replace("wp-insights-sm.s3.ap-south-1.amazonaws.com","d199amilqw5tyr.cloudfront.net", $row["imageUrl"]);
				$basename = basename($row["imageUrl"]);			
				$filename = dirname($row["imageUrl"]);				
				
				$row['thumbnailImageURL'] = $filename .'/'. $basename;
				
				//Commented by YKV to avoid img.steelmint.com broken image issue - 11 Feb'23
				/*
				$row['thumbnailImageURL'] = $filename . "/tr:ar-2-1,w-200,c-at_max/" . $basename;
    			if($resourceType=='web'){
    				$row['imageUrl'] = $filename . "/tr:ar-2-1,w-800,c-at_max/" . $basename;
    			}
				*/
				//$row["ad_image"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", $row["ad_image"]);
				
				if(isset($filters['debug']) && $filters['debug'] == 1) {
					echo date("D") . ' -- ' . $cnt . "<br />";
				}
				
				$row['authorDetails'] = array(
											"authorID"=>intval($row['author_id']),
											"name"=>$row['author_name'],
											"emailId"=>$row['author_email']
										);
				$row["fbCommodity"] ='';
				if($row["commodityName"])
					$row["fbCommodity"] = $row["commodityName"];
				if($row["cn1"])
					$row["fbCommodity"] = $row["cn1"];
				
				$result["button_image"] = "";
				
				$result["Intels"][] = $row;
				/*if(
					(date("D") == "Mon" || date("D") == "Tue" || date("D") == "Wed") && 
					$cnt == 3 && 
					!isset($filters['dontShowAd']) &&
					!isset($filters["intelInsideInsight"])
				)*/
				$row["button_image"] = "";				
				/*if(
					$cnt == 1 && 
					!isset($filters['dontShowAd']) &&
					!isset($filters["intelInsideInsight"])
				){
					$row["itemID"]=4536;
					$row["commodityName"]="";
					$row["cn"]="";
					$row["cn1"]="";
					$row["title"]="";
					$row["description"]="";
					$row["datePublished"]="2021-04-07 16:33:51";
					$row["postedDateTime"]="2021-04-07 16:33:51";
					$row["added_at"]="";
					$row["thumbnailImageURL"]="";
					$row["ad_image"] = "https://www.steelmint.com/fileForMail/engage4_with.jpg";
                    $row["imageUrl"] = "https://www.steelmint.com/fileForMail/engage4_with.jpg";
                   
                    if(isset($filters['newIntelLayout']) && !empty($filters['newIntelLayout'])){
							$row["ad_image"] = "https://www.steelmint.com/fileForMail/engage4_without.jpg";
							$row["imageUrl"] = "https://www.steelmint.com/fileForMail/engage4_without.jpg";
							$row["button_image"] = "https://www.steelmint.com/fileForMail/engage_button.png";
					}
                    $row["ad_action"] = "open_url";
                    $row["type"] = "image";
                    $row["isAd"] = "y";
					$row["url_screen_name"]="https://tinyurl.com/4v6ys5kb"; 
					$row["href"]="https://tinyurl.com/4v6ys5kb";				
					$row["videoUrl"]="";
					$result["Intels"][] = $row;
					
				}
				if(
					$cnt == 2 && 
					!isset($filters['dontShowAd']) &&
					!isset($filters["intelInsideInsight"])
				){
					$row["itemID"]=4536;
					$row["commodityName"]="";
					$row["cn"]="";
					$row["cn1"]="";
					$row["title"]="";
					$row["description"]="";
					$row["datePublished"]="2021-04-07 16:33:51";
					$row["postedDateTime"]="2021-04-07 16:33:51";
					$row["added_at"]="";
					$row["thumbnailImageURL"]="";
					$row["ad_image"] = "https://www.steelmint.com/fileForMail/coal_wb.png";
                    $row["imageUrl"] = "https://www.steelmint.com/fileForMail/coal_wb.png";					      
                    if(isset($filters['newIntelLayout']) && !empty($filters['newIntelLayout'])){
							$row["ad_image"] = "https://www.steelmint.com/fileForMail/coal_wob.png";
							$row["imageUrl"] = "https://www.steelmint.com/fileForMail/coal_wob.png";
							$row["button_image"] = "https://www.steelmint.com/fileForMail/btn_29may.png";             
					}
                    $row["ad_action"] = "open_url";
                    $row["type"] = "image";
                    $row["isAd"] = "y";
					$row["url_screen_name"]="https://tinyurl.com/5dze35u5"; 
					$row["href"]="https://tinyurl.com/5dze35u5";
					$row["videoUrl"]="";
					$result["Intels"][] = $row;
					
				}
				if(
					$cnt == 3 && 
					!isset($filters['dontShowAd']) &&
					!isset($filters["intelInsideInsight"])
				){
					$row["itemID"]=4536;
					$row["commodityName"]="";
					$row["cn"]="";
					$row["cn1"]="";
					$row["title"]="";
					$row["description"]="";
					$row["datePublished"]="2021-04-07 16:33:51";
					$row["postedDateTime"]="2021-04-07 16:33:51";
					$row["added_at"]="";
					$row["thumbnailImageURL"]="";
					$row["ad_image"] = "https://www.steelmint.com/fileForMail/io_wb.png";
                    $row["imageUrl"] = "https://www.steelmint.com/fileForMail/io_wb.png";					      
                    if(isset($filters['newIntelLayout']) && !empty($filters['newIntelLayout'])){
							$row["ad_image"] = "https://www.steelmint.com/fileForMail/io_wob.png";
							$row["imageUrl"] = "https://www.steelmint.com/fileForMail/io_wob.png";
							$row["button_image"] = "https://www.steelmint.com/fileForMail/btn_29may.png";             
					}
                    $row["ad_action"] = "open_url";
                    $row["type"] = "image";
                    $row["isAd"] = "y";
					$row["url_screen_name"]="https://tinyurl.com/bd92bna6"; 
					$row["href"]="https://tinyurl.com/bd92bna6";
					$row["videoUrl"]="";
					$result["Intels"][] = $row;
					
				}*/
				if(
					$cnt == 2 && 
					!isset($filters['dontShowAd']) &&
					!isset($filters["intelInsideInsight"])
				){
					$row["itemID"]=4536;
					$row["commodityName"]="";
					$row["cn"]="";
					$row["cn1"]="";
					$row["title"]="";
					$row["description"]="";
					$row["datePublished"]="2021-04-07 16:33:51";
					$row["postedDateTime"]="2021-04-07 16:33:51";
					$row["added_at"]="";
					$row["thumbnailImageURL"]="";
					$row["ad_image"] = "https://www.steelmint.com/fileForMail/ismc_with_button.png";
                    $row["imageUrl"] = "https://www.steelmint.com/fileForMail/ismc_with_button.png";					      
                    if(isset($filters['newIntelLayout']) && !empty($filters['newIntelLayout'])){
							$row["ad_image"] = "https://www.steelmint.com/fileForMail/ismc_wo_button1.png";
							$row["imageUrl"] = "https://www.steelmint.com/fileForMail/ismc_wo_button1.png";
							$row["button_image"] = "https://www.steelmint.com/fileForMail/ismc_button1.png";             
					}
                    $row["ad_action"] = "open_url";
                    $row["type"] = "image";
                    $row["isAd"] = "y";
					$row["url_screen_name"]="http://tinyurl.com/yckbbbcd"; 
					$row["href"]="http://tinyurl.com/yckbbbcd";
					$row["videoUrl"]="";
					$result["Intels"][] = $row;
					
				}
                /*if(
					(date("D") == "Tue" || date("D") == "Thu") &&
					$cnt == 3 && 
					!isset($filters['dontShowAd']) &&
					!isset($filters["intelInsideInsight"])
				){
					$row["itemID"]=4536;
					$row["commodityName"]="";
					$row["cn"]="";
					$row["cn1"]="";
					$row["title"]="";
					$row["description"]="";
					$row["datePublished"]="2021-07-03 16:33:51";
					$row["postedDateTime"]="2021-07-03 16:33:51";
					$row["added_at"]="";
					$row["thumbnailImageURL"]="";
					$row["ad_image"] = "https://www.steelmint.com/fileForMail/minera_with_button1.jpg";
                    $row["imageUrl"] = "https://www.steelmint.com/fileForMail/minera_with_button1.jpg";
					if(isset($filters['newIntelLayout']) && !empty($filters['newIntelLayout'])){
							$row["ad_image"] = "https://www.steelmint.com/fileForMail/minera_without_button1.jpg";
							$row["imageUrl"] = "https://www.steelmint.com/fileForMail/minera_without_button1.jpg";
							$row["button_image"] = "https://www.steelmint.com/fileForMail/button_minera.png";             
					}
                    $row["ad_action"] = "open_url";
                    $row["type"] = "image";
                    $row["isAd"] = "y";
					$row["url_screen_name"]="http://bit.ly/3hkJVGO"; 
					$row["href"]="http://bit.ly/3hkJVGO";
					$row["videoUrl"]="";
					$result["Intels"][] = $row;
					
				}*/
				$cnt += 1;
			}
			
            $result["intelCount"] = $tc;
            
		/* if( $posOf5thItem > -1 && $offset == 0 ){
			$result["Intels"] = \ApiQuery::moveElement($result["Intels"], $posOf5thItem, 4);
		}
		if( $posOf7thItem > -1 && $offset == 0 ){
			$result["Intels"] = \ApiQuery::moveElement($result["Intels"], $posOf7thItem, 6);
		} */
		
		/* if(isset($filters['debug']) && $filters['debug'] == 1) {
			echo "posOf5thItem:" . $posOf5thItem;
			if( $posOf5thItem > 0 && $offset == 0 ){
				$result["Intels"] = \ApiQuery::moveElement($result["Intels"], $posOf5thItem, 4);
			}
			echo "<pre>";
			print_r($result["Intels"]);	
		} */
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
			
			
         return $result;
    }
    
    public static function moveElement($array, $a, $b) {
        $out = array_splice($array, $a, 1);
        array_splice($array, $b, 0, $out);
        return $array;
    }	
		
    ///Intel List
	//DEFAULT_LIMIT
    public static function getIntelRowSet_13_5_2020($memid=0,$resourceType="app", $type='', $filters=array(), $pageType='post', $limit=5, $offset=0, $appType='SM'){
		////include_once "/home/steelmin/public_html/inc/config1.php"; 
        $result=array(); 
        if($resourceType=="web"){       
           $sql = "SELECT `itemID`, (select itemName from tbl_region_commodity_master as cm where intel.subCommodityId=cm.id and itemType='commodity') as commodityName, `title`, `description`, `videoUrl`, `imageUrl`, `videoUrl`, `datePublished`, `type`, `isAd`, `ad_image`, `ad_action`, `url_screen_name`, `created_at` FROM `intel` WHERE itemId>0 ";
        } else {

			if($pageType == "pre" || $pageType == "pre_1")	
			   $no_ad = ' AND isAd="n" ';
			else
			   $no_ad = "";  

           $sql = "SELECT   `itemID`,
                            (select itemName from tbl_region_commodity_master as cm where intel.subCommodityId=cm.id and itemType='commodity') as commodityName,
                            `title`, `description`, `videoUrl`, `imageUrl`, `videoUrl`, `datePublished`, `type`, `isAd`, `ad_image`, `ad_action`, `url_screen_name`, `created_at` FROM `intel` WHERE itemId>0 $no_ad ";  
        }   
        $source =='';
		if(isset($filters['source'])) {//source
			$source = $filters['source'];
			switch($source){				
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark':
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
					/* $bookMarkedIds = qryToCommaSepString("select lead_id from tbl_bookmark as b where  user_id=$memid and section='intel' and appType ='$appType' ");
					if($bookMarkedIds)
						$filter['itemID'] = explode(',', $bookMarkedIds);
					else
						$filter['itemID'] = 0; */
					$common = new Common();
					$bookMarkedIds = $common->getUserBookmarksV2019($resourceType, $memid, $section='intel', $status='', $event_id=0);
					if(count($bookMarkedIds)>0)
						$filters['itemID'] = explode(',', $bookMarkedIds);
					else
						$filters['itemID'] = 0;
				break;
				case 'portfolio':
                   /*  $common = new Common();
					$temp = $common->getUserPortfolioV2019($memid, 'news', $appType);		
					print_r($temp); */
					// and appType='".$appType."'
					$sqlTC = "select regionId, commodityID from tbl_user_portfolio where user_id=".$memid." and type='intel' order by id desc limit 1"; 
					$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
					$temp = mysql_fetch_array($rsTC,MYSQL_ASSOC);					
					
					if($temp['commodityID']){
						$commodityIDs = $temp['commodityID'];
						$filters['commodityID'] = explode(',',$commodityIDs);
					}
					if($temp['regionId']){
						$regionIDs = $temp['regionId'];
						$filters['regionID'] = explode(',',$regionIDs);
					}
					
					if(empty($filters['commodityID']) && empty($filters['regionID'])){
						return $result;
					}
					//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
			}
		}
		
		if(isset($filters['trendingTags']) && !empty($filters['trendingTags'])) {			
			//get trendingTags and pass as like in table intel
			$sql .= " AND FIND_IN_SET({$filters['trendingTags']},`trending_tag`) > 0 ";
		}
		
		if(isset($filters['commodityID'])) {
			$sql .= " AND (";
				$sql .= " `commodityID` IN (";
				$sql .= implode(", ", $filters['commodityID']);
				$sql .= ")";
			$sql .= " OR ";	
				$sql .= " `subCommodityID` IN (";
				$sql .= implode(", ", $filters['commodityID']);
				$sql .= ")";
			$sql .= ")";
		}
		
		if(isset($filters['regionID'])) {
			$sql .= " AND (";
			foreach($filters['regionID'] as $k=>$regionID) {
				if($k>0)
					$sql .= " OR ";
				$sql .= "(regionID like '$regionID' or regionID like '$regionID,%' or regionID like '%,$regionID')";
			}
			$sql .= ")";
			//(regionIds like '$regionID' or regionIds like '9,%' or regionIds like '%,9')
		}
		
		if(isset($filters['itemID'])) {
			if(is_array($filters['itemID']))
				$sql .= " AND `itemId` IN (" . implode(',',$filters['itemID']) .")"; 
			else
				$sql .= " AND `itemId` = " . (int)$filters['itemID'];
		}

		if(isset($filters['not_in'])) {
			if(is_array($filters['not_in']))
				$sql .= " AND `itemId` NOT IN (" . implode(',',$filters['itemID']) .")"; 
			else
				$sql .= " AND `itemId` <> " . (int)$filters['not_in'];
		}
		
		$user = new User($memid, $appType);
		$isAccessible =  $user->isAccessible($resourceType, $section='Intel');
		
		if($isAccessible==-1){//post
		    if(!empty(Session::get('sectionFromDate'))){			
			    $sectionFromDate = Session::get('sectionFromDate');
		    
		    	$sql .= " AND datePublished >= '$sectionFromDate'";			
		    }else{
				$sql .= " AND datePublished = '2001-01-01'";	
			}
		}
		
		//print_r($filters['orderBy']);
		if(isset($filters['orderBy'])) {
			$sql .= " order BY {$filters['orderBy']} desc";
		} else{
			$sql .= " order BY itemId desc";

		}
		
		if($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		else
			$limit = DEFAULT_LIMIT;

		if($pageType == "pre")	
		    $limit = 2;
		else if($pageType == "pre_1")
			$limit = 1;
			
			
			if($limit)
				 $sql .= " LIMIT {$offset},{$limit}";

			//echo "sql:" . $sql;
            $query = mysql_query($sql);
            while($row = mysql_fetch_assoc($query)){
                $time_ago = strtotime($row["created_at"]);
                $cur_time   = time();
                $time_elapsed   = $cur_time - $time_ago;
                $seconds    = $time_elapsed ;
                $minutes    = round($time_elapsed / 60 );
                $hours      = round($time_elapsed / 3600);
                $days       = round($time_elapsed / 86400 );
                $weeks      = round($time_elapsed / 604800);
                $months     = round($time_elapsed / 2600640 );
                $years      = round($time_elapsed / 31207680 );
                // Seconds
                if($seconds <= 60){
                    $row["added_at"] = "just now";
                }
                //Minutes
                else if($minutes <=60){
                    if($minutes==1){
                        $row["added_at"] = "one minute ago";
                    }
                    else{
                        $row["added_at"] =  "$minutes minutes ago";
                    }
                }
                //Hours
                else if($hours <=24){
                    if($hours==1){
                        $row["added_at"] =  "an hour ago";
                    }else{
                        $row["added_at"] =  "$hours hrs ago";
                    }
                }
                //Days
                else if($days <= 7){
                    if($days==1){
                        $row["added_at"] =  "yesterday";
                    }else{
                        $row["added_at"] =  "$days days ago";
                    }
                }
                //Weeks
                else if($weeks <= 4.3){
                    if($weeks==1){
                        $row["added_at"] =  "a week ago";
                    }else{
                        $row["added_at"] =  "$weeks weeks ago";
                    }
                }
                //Months
                else if($months <=12){
                    if($months==1){
                        $row["added_at"] =  "a month ago";
                    }else{
                       $row["added_at"] =  "$months months ago";
                    }
                }
                //Years
                else{
                    if($years==1){
                        $row["added_at"] = "one year ago";
                    }else{
                        $row["added_at"] =  "$years years ago";
                    }
                }
                
                $row["itemID"] =  intval($row["itemID"]);
				$row["title"] = utf8_decode( stripslashes(html_entity_decode($row['title'], ENT_QUOTES)));	
				$row["description"] = utf8_decode(stripslashes(html_entity_decode($row['description'], ENT_QUOTES)));
				$row["ad_image"] = "https://www.steelmint.com/fotomine/api/public/fotomine/images/99-80/jamshedur-plant-2-99-80-5c1c8148453d9.jpg";
				$row["ad_action"] = "open_screen";
				$row["url_screen_name"] = "https://www.steelmint.com/web_app.php?source=ironOre";
				unset($row["created_at"]);
				if($pageType == "pre"){
					$row["is_new"] = "Y";
				}else if($pageType == "pre_1"){
					$row["is_new"] = "Y";
				}else{
                    $row["is_new"] = "N";
				}
				//$row["imageUrl"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", $row["imageUrl"]);
                $result["Intels"][] = $row;
                
			}
			


         return $result;
    }
	//DEFAULT_LIMIT
    public static function getPhotoRowSet($filters=array(), $pageType='post', $limit=5, $offset=0, $appType='SM'){
        //include_once "/home/steelmin/public_html/inc/config1.php"; 
        $sql = "SELECT views, `id` AS `itemID`, `title`, `description`, `updated_at` AS `postedDateTime` FROM `fotomine_posts` WHERE `status` = '1'";   
        //$sql .= " order by id desc";   
        if($appType=='CM')
			$sql .= " and category = 'coal'";  
			
            switch($pageType){
               case 'post':
                        if(isset($filters["title"]) && $filters["title"] != null)
                                $sql .= " and f.`title` LIKE' %{$filters['title']}%";
		
						$sql .= " order by postedDateTime desc";  
                        if($limit)
                             $sql .= " limit {$offset},{$limit}";
					
               break;
               case 'pre':
					$sql .= " order by postedDateTime desc";  
                     $sql .= " limit {$limit}";
               break; 
            }
			//echo $sql;
			
			
            $query = mysql_query($sql);
            while($rowk = mysql_fetch_assoc($query)){
                $secondary  = mysql_query("SELECT fp.id,fp.type,fp.path,fp.updated_at,fp.views FROM fotomine_post_images fp WHERE fp.status IN (1,2) AND fp.post_id=".$rowk["itemID"]);
                $gallery = array();
				
				$views=0; $i = 0;
                while($row = mysql_fetch_array($secondary)){
                    //echo $i . "--";
                    if($row['type'] == "I" ){
                       $gallery[] = array(
											"ID"		=>	$row["id"],
											//"mainImage"	=>	str_replace("https://www.steelmint.com","https://img.steelmint.com", $row["path"]),
											"mainImage"	=>	$row["path"],
											"videoUrl"	=>	"",
											"type"		=>	$row['type']
										);
						if( $i == 0 ){
							$thumbImage = $row["path"];
							$type = "I";
							$i = 1;
						}
					}  
                    else{
							$exp_v = explode("=",$row["path"]);// sample format https://www.youtube.com/watch?v=fV7PD90qcUw&feature=youtu.be
							$gallery[] = array("ID"=>$row["id"],"mainImage"=>str_replace("&feature","","https://img.youtube.com/vi/{$exp_v[1]}/hqdefault.jpg"),"videoUrl"=>$row["path"],"type"=>$row['type']); 
							if( $i == 0 ){
								$thumbImage = "https://img.youtube.com/vi/{$exp_v[1]}/hqdefault.jpg";								$type = "V";
								$i = 1;
							}
							$thumbImage = str_replace("&feature","",$thumbImage);
					}
					$views += $row["views"];
                }
				//$thumbImage = str_replace("https://www.steelmint.com","https://img.steelmint.com", $thumbImage);
				//$thumbImage .= "?tr=h-184,w-300";
				$rowk["gallery"] = $gallery;
				//$rowk["thumbImage"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", $thumbImage) . "?tr=h-475,w-1080";
				$rowk["thumbImage"] = $thumbImage . "?tr=h-475,w-1080";
				$rowk["postedDateTime"] = date('M d, Y H:i', strtotime($rowk['postedDateTime']));
                $rowk["totalViews"] = $views + $rowk["views"];
                $rowk["type"] = $type;
				$rowk['description'] = removeMSWordattributes(html_entity_decode($rowk['description'], ENT_QUOTES));
                $result[] = $rowk;
            }
            //echo "<pre>";
			//print_r($result);
         //include_once "/home/steelmin/public_html/inc/desconfig.php";
         return $result;
    }

    public static function updateViews($views=array()){
        //include_once "/home/steelmin/public_html/inc/config1.php"; 
        if(mysql_query("UPDATE `fotomine_post_images` SET `views`= `views` + {$views['count']} WHERE `id`={$views['ID']}")){
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return true;
        } else {
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
            return false;
        }
    }


	public static function getAccomodationRowSet($event_id=''){
        //include_once "/home/steelmin/public_html/inc/config1.php";
        
            $whrcond = " (  event_id = $event_id ) ";
        
            $sql = " SELECT id AS `itemID`,`name`,`event_id` AS `eventID`, distance_frm_venue AS `distanceFromVenue`, price_per_night AS `pricePerNight`, website, `address`, `location`, email, phone_no AS `phoneNo`, concat('https://www.steelmint.com/sm_group_events/images/events/accomodation/', thumb_image) AS `thumbImage`, images, f_description AS `description` , f_rating AS `rating`,`contactPerson`,`contactDesignation`,`contactMobile`,`contactEmail` FROM tbl_sm_events_accomodation
                WHERE $whrcond ";
        
            $rs = mysql_query($sql)or die(mysql_error().$sql);
        
            $_rs_array = array();
        
            while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
                if($row['images']){
                    $a =  "https://www.steelmint.com/sm_group_events/images/events/accomodation/" . str_replace(",", ',https://www.steelmint.com/sm_group_events/images/events/accomodation/', $row['images']);
                    $row['images'] = explode(',', $a);
                }else
                    $row['images'] = array();		
                $row['description'] = removeMSWordattributes(html_entity_decode($row['description'], ENT_QUOTES));
                $_rs_array[]= $row;
            }
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
            return $_rs_array;

    }

    public static function getSponsorOrExibRowSet($event_id='', $type=''){
        //include_once "/home/steelmin/public_html/inc/config1.php";
    
        $whrcond = " (  event_id = $event_id ) ";
		if($event_id == 84 || $event_id == 85 || $event_id == 86)
			$whrcond = " (  event_id in (84,85,86) ) ";
    
        if(''!=$type)
            $whrcond .= " AND sponser_or_exhibitor = '$type'";
        $sql = "
			select id , event_id, sponser_type, company, logo, location, sponser_website_link, sponser_or_exhibitor,companyType,aboutCompany,ceo,headQuarters,email,phoneno,founded,noOfEmployees,hallName,
			stallNo,floorImgUrl,floorWebUrl from tbl_sm_events_sponsors
            where $whrcond
            order by 
            CASE 		
                WHEN sponser_type = 'Principal Sponsor' then 1
                WHEN sponser_type = 'Platinum Sponsor' then 2
                WHEN sponser_type = 'Associate Platinum Sponsor' then 3
                WHEN sponser_type = 'Gold Sponsor' then 4
                WHEN sponser_type = 'Silver Sponsor' then 5
                WHEN sponser_type = 'Lunch Sponsor' then 6
                WHEN sponser_type = 'Delegate Sponsor' then 7
                WHEN sponser_type = 'Delegate Kit Sponsor' then 8
                WHEN sponser_type = 'Associate Sponsor' then 9
                ELSE 99
            END
        ";
    
        $rs = mysql_query($sql)or die(mysql_error().$sql);
    
        $_rs_array = array();
    
        $_rs_array['exhibitors'] = [];
    
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
            $thumb ='';$image='';
            if($row['logo']){
                $thumb = 'https://www.steelmint.com/sm_group_events/images/events/sponsers/thumb_'.$row['logo'];
                $image = 'https://www.steelmint.com/sm_group_events/images/events/sponsers/'.$row['logo'];
			}
			
            if($row['sponser_or_exhibitor']=='sponsor'){
                $_rs_array['sponsors'][] = array(
                    'sponsorID'        => intval($row['id']) ,
                    'eventID'  => intval($row['event_id']),
                    'name'      => removeMSWordattributes(html_entity_decode($row['company'], ENT_QUOTES)),
                    'companyType' => $row['companyType'],
                    'aboutCompany'=> $row['aboutCompany'],
                    'ceo' => $row['ceo'],
                    'headQuarters' => $row['hq'],
                    'email'    =>$row['email'],
                    'phone'   => $row['phoneno'],
                    'founded' => $row['founded'],
                    'noOfEmployees' => $row['noOfEmployees'],
                    'companyWebsite' => $row['sponser_website_link'],
                    'logo' => $image,
                    'category'=>$row['sponser_type']
                );
                
    
            }else if ($row['sponser_or_exhibitor']=='exhibitor'){
                $_rs_array['exhibitors'][] = array(
                    'exhibitorID' => intval($row['id']) ,
                    'eventID'  => intval($row['event_id']),
                    'name'      =>removeMSWordattributes(html_entity_decode($row['company'],ENT_QUOTES)),
                    'companyType' => $row['companyType'],
                    'aboutCompany'=> $row['aboutCompany'],
                    'ceo' => $row['ceo'],
                    'headQuarters' => $row['hq'],
                    'email'    =>$row['email'],
                    'phone'   => $row['phoneno'],
                    'founded' => $row['founded'],
                    'noOfEmployees' => $row['noOfEmployees'],
                    'hallName' => removeMSWordattributes(html_entity_decode($row['hallName'],ENT_QUOTES)),
                    'stallNo' => $row['stallNo'],
                    'floorImgUrl'=> $row['floorImgUrl'],
                    'floorWebUrl'=> $row['floorWebUrl'],
                    'companyWebsite'=> $row['sponser_website_link'],
                    'logo'=>$image,
                    'category'=>$row['sponser_type']
                );
               
            }
        }
         //include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $_rs_array;
    }

public static function getAccomodationRowSet_new($event_id=''){
        $_rs_array = array();

        $file_path = specificEventsJsonEndPoint . "$event_id/event_accommodations.json";

        // Read the JSON file
        $json_content = file_get_contents($file_path);
        
        // Decode JSON data to PHP array
        $data = json_decode($json_content, true);
        // echo "<pre>";
        // print_r($data);
        // Check if JSON decoding was successful
        if ($data === null) {
            return array();
            die('Error decoding JSON');
        }    
        
        // echo "<pre>";
        // print_r($data);
        
        $row = array();
        foreach ($data["accommodations"] as $sponsor) {
            $image = htmlspecialchars('https://d2muc4gjue24u0.cloudfront.net/common/images/' . 'common/' . $sponsor['photoUrl'] . '.webp');
            $row['itemID'] = "0";
            $row['name'] = $sponsor['name'];
            $row['eventID'] = $event_id;
            $row['distanceFromVenue'] = trim($sponsor['distanceFromVenue']);
            $row['pricePerNight'] = trim($sponsor['pricePerNight']);
            $row['website'] = $sponsor['website'];
            $row['address'] = trim($sponsor['address']);
            $row['location'] = trim($sponsor['location']);
            $row['email'] = $sponsor['email'];
            $row['phoneNo'] = trim($sponsor['phone']);
            $row['thumbImage'] = $image;
            $row['images'] = array($image);
            $row['description'] = $sponsor['description'];

            $row['rating'] = trim($sponsor['rating']);
            $row['contactPerson'] = trim($sponsor['contactPerson']);
            $row['contactDesignation'] = trim($sponsor['contactDesignation']);
            $row['contactMobile'] = trim($sponsor['phone']);
            $row['contactEmail'] = $sponsor['email'];



            $_rs_array[]= $row;
        }
        return $_rs_array;
    }

    public static function getSponsorOrExibRowSet_new($event_id='', $type=''){
        
// if($type!='sponsor'){
//  include_once "/home/steelmin/public_html/api/storage/v2019/event/exhibitor_list.php";
//  $result['exhibitors'] = $result;
//     } 
// else {
// include_once "/home/steelmin/public_html/api/storage/v2019/event/sponsor_list.php";
// $result['sponsors'] = $result;
//     } 


//           return $result;
//          die;        

        $_rs_array = array();


        if($type=='sponsor'){
            $arrKey = "sponsors";
            $file_path = specificEventsJsonEndPoint . "$event_id/event_sponsor_page.json";
            $_rs_array['sponsors'] = [];        
        } else {
            $arrKey = "exhibitors";
            $file_path = specificEventsJsonEndPoint . "$event_id/event_exhibitor_page.json";
            $_rs_array['exhibitors'] = [];
        }
        
        
        // Read the JSON file
        $json_content = file_get_contents($file_path);
        
        // Decode JSON data to PHP array
        $data = json_decode($json_content, true);
        
        // Check if JSON decoding was successful
        if ($data === null) {
            return array();
            die('Error decoding JSON');
        }    
        
        // echo "<pre>";
        // print_r($data);
        
        
        foreach ($data[$arrKey] as $sponsor) {
            $image = htmlspecialchars('https://d2muc4gjue24u0.cloudfront.net/common/images/' . 'company-logo/' . $sponsor['slug'] . '.webp');

            if($type=='sponsor'){
                $_rs_array['sponsors'][] = [
                    'sponsorID' => 0, // Replace with actual sponsor ID if available
                    'eventID' => intval($event_id), // Replace with actual event ID if available
                    'name' => $sponsor['sponsorDetails']['name'],
                    'companyType' => $sponsor['pocDetails']['companyType'],
                    'aboutCompany' => $sponsor['pocDetails']['aboutCompany'],
                    'ceo' => $sponsor['pocDetails']['ceo'],
                    'headQuarters' => $sponsor['pocDetails']['headQuarters'],
                    'email' => $sponsor['pocDetails']['email'],
                    'phone' => $sponsor['pocDetails']['contact'],
                    'founded' => $sponsor['pocDetails']['founded'],
                    'noOfEmployees' => $sponsor['pocDetails']['noOfEmployees'],
                    'companyWebsite' => $sponsor['pocDetails']['website'],
                    'logo' => $image,
                    'category' => $sponsor['sponsorDetails']['designation']
                ];
                
    
            }else if ($type=='exhibitor'){
                $_rs_array['exhibitors'][] = [
                    'exhibitorID' => 0,
                    'eventID' => intval($event_id),
                    'name' => isset($sponsor['name']) ? $sponsor['name'] : '',
                    'companyType' => isset($sponsor['companyType']) ? $sponsor['companyType'] : '',
                    'aboutCompany' => isset($sponsor['aboutCompany']) ? $sponsor['aboutCompany'] : '',
                    'ceo' => isset($sponsor['ceo']) ? $sponsor['ceo'] : '',
                    'headQuarters' => isset($sponsor['headQuarters']) ? $sponsor['headQuarters'] : '',
                    'email' => isset($sponsor['pocDetails']['email']) ? $sponsor['pocDetails']['email'] : '',
                    'phone' => isset($sponsor['pocDetails']['contact']) ? $sponsor['pocDetails']['contact'] : '',
                    'founded' => isset($sponsor['founded']) ? $sponsor['founded'] : '',
                    'noOfEmployees' => isset($sponsor['noOfEmployees']) ? $sponsor['noOfEmployees'] : '',
                    'hallName' => isset($sponsor['hallName']) ? $sponsor['hallName'] : '',
                    'stallNo' => isset($sponsor['pocDetails']['stallNo']) ? $sponsor['pocDetails']['stallNo'] : '',
                    'floorImgUrl' => isset($sponsor['floorImgUrl']) ? $sponsor['floorImgUrl'] : '',
                    'floorWebUrl' => isset($sponsor['floorWebUrl']) ? $sponsor['floorWebUrl'] : '',
                    'companyWebsite' => isset($sponsor['pocDetails']['website']) ? $sponsor['pocDetails']['website'] : '',
                    'logo' => isset($image) ? $image : '',
                    'category' => isset($sponsor['designation']) ? $sponsor['designation'] : ''
                ];

            }
        }
         //include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $_rs_array;            
    }

public static function getSpeakersRowSet_new($event_id=''){
        
        
      
        //  include_once "/home/steelmin/public_html/api/storage/v2019/event/eventSpeaker.php";
        //   return $result;
        //  die;        
        
        $file_path = specificEventsJsonEndPoint . "$event_id/event_speaker_page.json";        
        
        // Read the JSON file
        $json_content = file_get_contents($file_path);
        
        // Decode JSON data to PHP array
        $data = json_decode($json_content, true);
        
        // Check if JSON decoding was successful
        if ($data === null) {            
            return array();
            die('Error decoding JSON');
        }    
        
        // echo "<pre>";
        // print_r($data);     
        
        $schedule = array();
        $past_events = array();
        
        foreach ($data["teamSingle"]["sections"] as $sponsor) {
            $image = '';
            $flag = '';
            
            if( "" != $sponsor['slag'] )
                $image = htmlspecialchars('https://d2muc4gjue24u0.cloudfront.net/common/images/' . 'entity/' . $sponsor['slag'] . '.webp');

            if( "" != $sponsor['details']['country_code'])
                $flag = "https://www.steelmint.com/steeladmin/flags/".strtolower($sponsor['details']['country_code']).".png";

            foreach ($sponsor['sessions'] as $sessions) {
                if( "" != $sessions['events']['sessionTitle'] ) {
                    $session["sessionID"] = 0;
                    $session["sessionDesc"] = $sessions['events']['description'];
                    $session["sessionTitle"] = $sessions['events']['sessionTitle'];
                    $schedule[] = $session;
                }
            }

            foreach ($sponsor['pastEvents'] as $past_event) {
                if( "" != $past_event['description'] ) {
                    $past_event["eventID"] = 0;
                    $past_event["description"] = $past_event['description'];
                    $past_events[] = $past_event;
                }
            }

            $_rs_array[] = array(
                'speakerID'            =>  0,
                'eventID'      =>  intval($event_id),
                'name'          =>  $sponsor['details']['name'],
				'designation'      =>  $sponsor['details']['designation'],
				'company'       =>  $sponsor['details']['companyName'] . ", " . $sponsor['details']['country'],
				'desc'          =>  $sponsor['details']['designation'],
                'linkdInUrl'    =>  $sponsor['details']['socialMedia']['LinkedIn'],
                'flag'          =>  $flag,
				'country'       =>  $sponsor['details']['country'],
				'addedOn'       => "",
                'isBookmarked'  => "",
                'thumbImg'     =>  $image,
                'mainImg'         =>  $image,
                'schedule'        =>  $schedule,
                'pastEvents'   =>  $past_events
            );
        }    
         return $_rs_array;
    }
public static function getSchedulesRowSet_new($event_id){
         
         
        //  include_once "/home/steelmin/public_html/api/storage/v2019/event/eventSchedule_list.php";
        //   return $result;
        //  die;
         $file_path = specificEventsJsonEndPoint . "$event_id/event_schedule.json";        
        
        // Read the JSON file
         $json_content = file_get_contents($file_path);
        
        // Decode JSON data to PHP array
        $data = json_decode($json_content, true);
        
        // Check if JSON decoding was successful
        if ($data === null) {
            return array();
            die('Error decoding JSON');
        }    
        
        //  echo "<pre>";
        //  print_r($data);     
        
        $schedule = array();
        $past_events = array();
        
        foreach ($data["schedule"]["tabs"] as $a) {
            foreach ($a["content"] as $schedule) {
                
                if( !($schedule['description'] == '' && $schedule['topic'] == '')  ){
                    $row["sessionID"] = 0;
                    $row["eventID"] = intval($event_id);
                    
                    // $duration_schedule = explode("-",$schedule["time"]);
                    // $v_st = strtotime($a["date"]." ".$duration_schedule[0].":00");
                    // $row["startTimeStamp"] = "{$v_st}";
                    // $v_et = strtotime($a["date"]." ".$duration_schedule[1].":00");
                    // $row["endTimeStamp"] = "{$v_et}";

                    // Remove the " IST" part from the time string
                    $time_str = str_replace(" IST", "", $schedule["time"]);
                    
                    // Check if the time string contains a dash ("-") indicating a range
                    if (strpos($time_str, '-') !== false) {
                        // Time range format: "09:30-10:30"
                        $duration_schedule = explode("-", $time_str);
                        
                        // Parse start and end times
                        $v_st = strtotime($a["date"] . " " . $duration_schedule[0] . ":00");
                        $row["startTimeStamp"] = "{$v_st}";
                        
                        $v_et = strtotime($a["date"] . " " . $duration_schedule[1] . ":00");
                        $row["endTimeStamp"] = "{$v_et}";
                    } else {
                        // Single time format: "8:00"
                        $v_st = strtotime($a["date"] . " " . $time_str . ":00");
                        $row["startTimeStamp"] = "{$v_st}";
                        
                        // No end time provided, set end time to start time for single time format
                        $row["endTimeStamp"] = "{$v_st}";
                    }


                    //$row["floorPlan"] = array("webUrl"=>$schedule["floorPlan"]["webUrl"],"imgUrl"=>$schedule["floorPlan"]["imgUrl"]);
                    $row["floorPlan"] = array("webUrl"=>"","imgUrl"=>"");
                    
                    $row["timeSlot"] =  $schedule['time'];
                    $row["sessionDesc"] =  html_entity_decode($schedule['description'], ENT_QUOTES);
                    $row["sessionTitle"] =  strip_tags(html_entity_decode($schedule['topic'], ENT_QUOTES));
                    $row["date"] = date("d M",strtotime($a["day"] . " " . $a["month"]));
                    $row["topics"] = array();
                    $row["isBookmarked"] = "";
                    $row["isReminderSet"] = "N";
                    $row['hallName'] ='';
                   
                    if(!empty($schedule['topics'])){
                      $row["topics"] =$schedule['topics'];
                    }
                 
                    if(isset($schedule['hall']) && !empty($schedule['hall'])){                       
                        if($schedule['hall']=='Pearl Ballroom'){                         
                            if($a['id']=='pills-1')
                                $row['hallName']='2. Pearl';
                            else
                                $row['hallName']='1. Pearl';
                            
                        }
                        elseif($schedule['hall']=='Royal Ballroom'){                            
                            if($a['id']=='pills-1')
                                $row['hallName']='3. Royal';
                            else
                                $row['hallName']='2. Royal';
                        }
                        elseif($schedule['hall']=='Refreshment'){                            
                            if($a['id']=='pills-1')
                                $row['hallName']='4. Refreshment';
                            else
                                $row['hallName']='3. Refreshment';
                        }
                        elseif($schedule['hall']=='Registration')
                            $row['hallName']='1. Registration';
                        else
                            $row['hallName'] = trim($schedule['hall']);
                    }
                    
                        
                    $result[] = $row;
                }
            }
        }		
        
        return $result;
    }

    public static function getSpeakersRowSet($event_id='',$speaker_id='',$bookmarks='',$is_bookmark=0){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$bookmark_array = explode(",",$bookmarks);
		$is_bookmarked = $is_bookmark;
        $sql = "SELECT es.`id`, ets.`event_id`, es.`name`, es.`designation`, es.`company`, c.`country`, c.`country_code`, es.`basic_profile`, es.`image`,es.`linkdInUrl`,es.`facebookUrl`,es.`f_date_time`" ;
        if($speaker_id==''){
            $sql .= " FROM `tbl_sm_events_speakers` es LEFT JOIN tbl_sm_event_to_speaker ets ON es.`id` = ets.`speaker_id` left join tbl_country c ON es.country=c.id  WHERE ets.`event_id` = " . $event_id . " order by  es.`name`";
        } else {
            $sql .= " FROM `tbl_sm_events_speakers` es LEFT JOIN tbl_sm_event_to_speaker ets ON es.`id` = ets.`speaker_id` left join tbl_country c ON es.country=c.id  WHERE ets.`event_id` = " . $event_id . " AND es.`id` = " . $speaker_id . " order by  es.`name`";
        } 
		
        $rs = mysql_query($sql)or die(mysql_error().$sql);
    
        $_rs_array = array();
    
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC)) {
            $thumb ='';
            $image='';
    
            if($row['image']){
                $thumb = 'https://www.steelmint.com/sm_group_events/images/events/speakers/thumb_'.$row['image'];
                $image = 'https://www.steelmint.com/sm_group_events/images/events/speakers/'.$row['image'];
            }
    
            $schedule = array();
            $sql = "SELECT `id` AS `sessionID`,`schedule_title` AS `sessionTitle`,`schedule_desciption` AS `sessionDesc`,`ppt_details` AS `pptUrl`,`dayOfEvent`,`formatted_time` AS `duration`,`hall_name` AS `location` FROM `tbl_sm_events_schedule` WHERE  FIND_IN_SET({$row['id']},`speaker_id`) > 0 and parent_id=0  AND `event_id` = " . $event_id;
            $sessionQuery = mysql_query($sql);
            if($sessionQuery != false && mysql_num_rows($sessionQuery) > 0) {
                while($session = mysql_fetch_assoc($sessionQuery)) {
					$session["sessionID"] = intval($session["sessionID"]);
					$session["sessionDesc"] = removeMSWordattributes(html_entity_decode($session['sessionDesc'], ENT_QUOTES));
					$session["sessionTitle"] = removeMSWordattributes(html_entity_decode($session['sessionTitle'], ENT_QUOTES));
                    $schedule[] = $session;
                }
            }

            $past_events = array();
            $sql = "SELECT e.`id` AS `eventID`, e.`event_name` AS `title`, e.`event_description` AS `description`, e.`event_venue` AS `location`, e.`event_type` AS `typeOfEvent`, e.`event_start_date` AS `date` FROM `tbl_sm_event_to_speaker` ets LEFT JOIN tbl_sm_events_events e ON e.`id` = ets.`event_id`  WHERE ets.`event_id` <> {$event_id} AND ets.`speaker_id` = {$row['id']}" ;
            $past_query = mysql_query($sql);
            if($past_query != false && mysql_num_rows($past_query) > 0) {
                while($past_event = mysql_fetch_assoc($past_query)) {
					$past_event["eventID"] = intval($past_event["eventID"]);
					$past_event["description"] = removeMSWordattributes(html_entity_decode($past_event['description'], ENT_QUOTES));
                    $past_events[] = $past_event;
                }
            }

			if($is_bookmarked){
				if(in_array($row['id'],$bookmark_array)){
					$_rs_array[] = array(
						'speakerID'            => intval($row['id']) ,
						'eventID'      =>  intval($row['event_id']),
						'name'          =>  removeMSWordattributes(html_entity_decode(str_replace(PHP_EOL, '', $row['name']), ENT_QUOTES)),
						'designation'      =>  removeMSWordattributes(html_entity_decode($row['designation'],ENT_QUOTES)),
						'company'       =>   removeMSWordattributes(html_entity_decode($row['company'] . ", " . $row['country'],ENT_QUOTES)),
						'desc'          =>  removeMSWordattributes(html_entity_decode($row['basic_profile'],ENT_QUOTES)),
						'linkdInUrl'    =>  $row['linkdInUrl'] ,
						'flag'          =>  "https://www.steelmint.com/steeladmin/flags/".strtolower($row['country_code']).".png",
						'country'       =>  $row['country'],
						'addedOn'       => $row['f_date_time'],
						'isBookmarked'  => "Y",
						'thumbImg'     =>  $thumb,
						'mainImg'         =>  $image,
						'schedule'        =>  $schedule,
						'pastEvents'   => $past_events
						);
				}
			} else {

				$_rs_array[] = array(
                'speakerID'            =>  intval($row['id']) ,
                'eventID'      =>  intval($row['event_id']),
                'name'          =>  removeMSWordattributes(html_entity_decode(str_replace(PHP_EOL, '', $row['name']), ENT_QUOTES)),
				'designation'      =>  removeMSWordattributes(html_entity_decode($row['designation'],ENT_QUOTES)),
				'company'       =>  removeMSWordattributes(html_entity_decode($row['company'] . ", " . $row['country'],ENT_QUOTES)),
				'desc'          =>  removeMSWordattributes(html_entity_decode($row['basic_profile'],ENT_QUOTES)),
                'linkdInUrl'    =>  $row['linkdInUrl'] ,
                'flag'          =>  "https://www.steelmint.com/steeladmin/flags/".strtolower($row['country_code']).".png",
				'country'       =>  $row['country'],
				'addedOn'       => $row['f_date_time'],
                'isBookmarked'  => in_array(intval($row['id']),$bookmark_array)?"Y":"N",
                'thumbImg'     =>  $thumb,
                'mainImg'         =>  $image,
                'schedule'        =>  $schedule,
                'pastEvents'   => $past_events
                );
			}
             
            
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $_rs_array;
    }

    public static function getSchedulesRowSet($event_id='',$alerts='',$bookmarks='',$is_bookmark=0,$type=''){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$result=array();
        $whrcond="1";
		$whrcond = " event_id = $event_id ";
		$bookmark_array = explode(",",$bookmarks);
		$alerts_array = explode(",",$alerts);
		$is_bookmarked = $is_bookmark;
        $sql ="select `id` AS `sessionID`, `schedule_title` AS `sessionTitle`,`schedule_desciption` AS `sessionDesc`,`schedule_date` AS `date`,`dayOfEvent`,`formatted_time` AS `timeSlot`, `hall_name` AS `hallName`,`ppt_details` AS `pptUrl` from tbl_sm_events_schedule where $whrcond and parent_id=0 order by f_datetime asc";
		$rs = mysql_query($sql)or die(mysql_error().$sql);
		
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){$topics = array();
             $sql_topic = "select `id` AS `topicID`, `topic_title` AS `topicTitle`,`topic_description` AS `topicDesc`, `formatted_time` AS `timeSlot`,`speaker_id`,`rating` from tbl_sm_events_schedule where $whrcond and parent_id={$row['sessionID']} order by `f_datetime` ASC";
            $topic_result = mysql_query($sql_topic) or die(mysql_error().$sql_topic); 
			  while($topic = mysql_fetch_array($topic_result,MYSQL_ASSOC)){$speakers = array();
				 //print_r($topic);
                 $explde = explode(",",$topic["speaker_id"]);
                 foreach($explde as $k=>$v){					if( '' != $v ){						$sql_speakers = "SELECT es.`id`, ets.`event_id`, es.`name`, es.`designation`, es.`company`, es.`country`, CONCAT('https://www.steelmint.com/sm_group_events/images/events/speakers/',es.`image`) AS `thumbImg` FROM `tbl_sm_events_speakers` es LEFT JOIN tbl_sm_event_to_speaker ets ON es.`id` = ets.`speaker_id` WHERE ets.`event_id` = " . $event_id . " AND es.`id` = {$v}" ;						 $speaker_result = mysql_query($sql_speakers) or die(mysql_error().$sql_speakers);						 $speaker = mysql_fetch_array($speaker_result,MYSQL_ASSOC);						 $speaker["id"] = intval($speaker["id"]);						 $speaker["event_id"] = intval($speaker["event_id"]);						 $speakers[] = $speaker;					}
                 }
                 unset($topic["speaker_id"]);
				 $duration_topic = explode("-",$topic["timeSlot"]);
				 $vt_st = strtotime($row["date"]." ".$duration_topic[0]);
				 $topic["startTimeStamp"] = "{$vt_st}";
				 $vt_et = strtotime($row["date"]." ".$duration_topic[1]);
				 $topic["endTimeStamp"] = "{$vt_et}";
				 
				 $topic["sessionID"] = intval($row["sessionID"]);
				 $topic["topicID"] = intval($topic["topicID"]);
				 $topic["eventID"] = intval($event_id);
				 $topic["speakers"] = $speakers;
				 $topic["topicTitle"] = removeMSWordattributes(html_entity_decode($topic['topicTitle'], ENT_QUOTES));
				 $topic["topicDesc"] = removeMSWordattributes(html_entity_decode($topic['topicDesc'], ENT_QUOTES));
				 $topic["isBookmarked"] = in_array($topic["topicID"],$bookmark_array)?"Y":"N";
				 $topic["isReminderSet"] = (in_array($topic["topicID"].'-active',$alerts_array) == FALSE && in_array($topic["topicID"].'-inactive',$alerts_array) == FALSE)?"":(in_array($topic["topicID"].'-active',$alerts_array)?"Y":"N");
				 $topic["rating"] = doubleval($topic["rating"]);
                 //unset($topic["timeSlot"]);
                 $topics[] = $topic;
                 
			  }
			  $row["sessionID"] = intval($row["sessionID"]);
			  $row["eventID"] = intval($event_id);
			  $duration_schedule = explode("-",$row["timeSlot"]);
			  $v_st = strtotime($row["date"]." ".$duration_schedule[0].":00");
			  $row["startTimeStamp"] = "{$v_st}";
			  $v_et = strtotime($row["date"]." ".$duration_schedule[1].":00");
			  $row["endTimeStamp"] = "{$v_et}";
			  $row["floorPlan"] = array("webUrl"=>$row["floor_plan_url"],"imgUrl"=>$row["floor_plan_imgUrl"]);
			  //$row["sessionDesc"] = filter_var($row["sessionDesc"], FILTER_SANITIZE_STRING,FILTER_FLAG_ENCODE_HIGH);
			  $row["sessionDesc"] =  removeMSWordattributes(html_entity_decode($row['sessionDesc'], ENT_QUOTES));
			  $row["sessionTitle"] =  removeMSWordattributes(html_entity_decode($row['sessionTitle'], ENT_QUOTES));
			  $row["date"] = date("d M",strtotime($row["date"]));
			  $row["topics"] = $topics;
			  $row["isBookmarked"] = in_array($row["sessionID"],$bookmark_array)?"Y":"N";
			  $row["isReminderSet"] = (in_array($row["sessionID"].'-active',$alerts_array) == FALSE && in_array($row["sessionID"].'-inactive',$alerts_array) == FALSE)?"":(in_array($row["sessionID"].'-active',$alerts_array)?"Y":"N");
			  //unset($row["timeRange"]);
			  if($is_bookmarked){
				if(in_array($row["sessionID"],$bookmark_array)){ 
					if($type!='topic'){
						$result[] = $row;
					} else {
						$result = $topics;
					}
				}
			  } else {
					$result[] = $row;
			  }		
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $result;
    }

    public static function getParticipantRowSet($event_id='',$bookmarks='',$is_bookmark=0,$memid=0){
        //include_once "/home/steelmin/public_html/inc/config1.php";
		 $bookmark_array = explode(",",$bookmarks);
		 $is_bookmarked = $is_bookmark;
         $cond = '';
		 $event_name = '';
		 $memidsall = 0;
         if($event_id!=''){
			 if($event_id == 73 || $event_id == 76){
					$memidsall =qryToCommaSepString("
				  SELECT 
					case 
						when delegates_ids <> '' then `delegates_ids`
						else registering_id
					end	
				  FROM `tbl_sm_events_payment_details`
				  WHERE event_id  in (73,76)
				  AND `registering_id`
				  IN (
					  SELECT registering_id
					  FROM `final_status`
					  WHERE (`closed` = 'Y')
					  AND eventid in (73,76)
				  )
				  AND `inv_no` <> ''            
				  UNION All        
				  SELECT registering_id
				  FROM `final_status`
				  WHERE (`complementary` = 'Y') AND `participant_type` not in ('organizer')
				  AND `eventid` in (73,76)");
			 }elseif($event_id == 84 || $event_id == 85 || $event_id == 86){
					$memidsall =qryToCommaSepString("
				  SELECT 
					case 
						when delegates_ids <> '' then `delegates_ids`
						else registering_id
					end	
				  FROM `tbl_sm_events_payment_details`
				  WHERE event_id  in (84,85,86)
				  AND `registering_id`
				  IN (
					  SELECT registering_id
					  FROM `final_status`
					  WHERE (`closed` = 'Y')
					  AND eventid in (84,85,86)
				  )
				  AND `inv_no` <> ''            
				  UNION All        
				  SELECT registering_id
				  FROM `final_status`
				  WHERE (`complementary` = 'Y') AND `participant_type` not in ('organizer')
				  AND `eventid` in (84,85,86)");
			 }else{
				 $memidsall =qryToCommaSepString("
				  SELECT 
					case 
						when delegates_ids <> '' then `delegates_ids`
						else registering_id
					end	
				  FROM `tbl_sm_events_payment_details`
				  WHERE event_id  = $event_id
				  AND `registering_id`
				  IN (
					  SELECT registering_id
					  FROM `final_status`
					  WHERE (`closed` = 'Y')
					  AND eventid = $event_id
				  )
				  AND `inv_no` <> ''            
				  UNION All        
				  SELECT registering_id
				  FROM `final_status`
				  WHERE (`complementary` = 'Y') AND `participant_type` not in ('organizer')
				  AND `eventid` = $event_id");
			 }
			 
					 //$cond = " WHERE sa.eventid={$event_id} and (sa.closed = 'Y' || sa.complementary = 'Y') ";
					 
			$sql2="select event_name from tbl_sm_events_events where id = $event_id";
				
			$rs2 = mysql_query($sql2)or die(mysql_error().$sql2);
			$row2 = mysql_fetch_array($rs2,MYSQL_ASSOC);
			$event_name=$row2['event_name'];
			if($event_id == 73 || $event_id == 76){
				$event_name = "Iron Ore & Coal Confrence 2022"; 
			}
         }
		 $mem_name='';
		 $mem_designation='';
		 $mem_company='';
		 if(!empty($memid) && $memid!=0){
			 $sql1="select CASE 
                    when billing_name = '' then name
                    else billing_name
                END as billing_name, 
                CASE 
                    when send_email_to = 'R' then email
                    else addtnl_email
                END as email, 
				isd_code,
                CASE 
                    when send_sms_to = 'R' then phoneno
                    else alternate_mob_no
                END as phoneno, 
                
                job_title, company from tbl_members where id = $memid";
				
				 $rs1 = mysql_query($sql1)or die(mysql_error().$sql1);
				 $row1 = mysql_fetch_array($rs1,MYSQL_ASSOC);
				 $mem_name=$row1['billing_name'];
				 $mem_designation=$row1['job_title'];
				 $mem_company=$row1['company'];
				 $emailid=$row1['email'];
				 $phonenumber = $row1['isd_code'].$row1['phoneno'];
				 
				 
		 }
		if(empty($memidsall)){
            return array();
		}
         $sql = "
            select 
                (SELECT short_comptype from tbl_companytype where id = d.companytype) as company_type,
                d.company_profile,
                d.profile_pic,d.id,d.facebook,d.linkedin,
                
                CASE 
                    when d.billing_name = '' then d.name
                    else d.billing_name
                END as billing_name, 
                 
                
                job_title, company,
                CASE 
                    when send_email_to = 'R' then email
                    else addtnl_email
                END as email, 
				isd_code,
                CASE 
                    when send_sms_to = 'R' then phoneno
                    else alternate_mob_no
                END as phoneno,
				c.country_code as 'flag',
				c.country,
				(select lastVisitiedOn from final_status where registering_id=d.id and eventid=$event_id) as lastVisitiedOn,
				d.share_contact
            from tbl_members d
            left join tbl_state_city sc
            ON d.country=sc.country_id
            AND d.state=sc.state_id
            AND d.city=sc.city_id
            left join tbl_country c
            ON d.country=c.id 
            where d.id in ($memidsall)           
            order by company
        ";
        $rs = mysql_query($sql)or die(mysql_error().$sql);
        $_rs_array = array();
     
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
            $image='';
            if($row['profile_pic']){
                $image = 'https://www.steelmint.com/images/clients/'.$row['profile_pic'];
                }
            
            if(strlen($row['location']) <= 3)
                $loctn = strtoupper($row['location']);
            else
				$loctn = ucwords(strtolower($row['location']));
            
            // if(	$row['id']=='26266')
                // $share_contact = 'Y';
            // else
                $share_contact = $row['share_contact'];
			if($is_bookmarked){
					if(in_array($row['id'],$bookmark_array)){ 
						$_rs_array[] = array(
							'attendeeID' => intval($row['id']),
							'chatID' => intval($row['id']),
							'eventID' => intval($event_id),
							'name'=> htmlspecialchars_decode (trim(str_replace(array("Mr.", "Mr", "Miss", "Miss."), "", $row['billing_name'])), ENT_QUOTES),
							'designation'=>$row['job_title'],
							'company'=> htmlspecialchars_decode($row['company'], ENT_QUOTES),
							'email'=>strtolower($row['email']),
							'phoneno'=>$row['isd_code'].$row['phoneno'],
							'linkdInUrl'=>$row['linkedin'],
							'addedOn' => $row['lastVisitiedOn'],							
							'flag'=> "https://www.steelmint.com/steeladmin/flags/" . strtolower($row['flag']) . ".png",
							'country'=>$row['country'],
							'thumbImgSmall'=>$image,
							'thumbImgLarge'=> $image,
							'isBookmarked'=>"Y",
							'textBody'=>"Dear ".trim($row['billing_name']).", this is ".$mem_name.", ".$mem_designation." at ".$mem_company.". With references to SteelMint ".$event_name.", I look forward to having a discussion with you. If this interests you, please reach out to me on " .$emailid." or ". $phonenumber.". Regards",
							'share_contact'=>$share_contact,
							'opt_out_text'=> 'This attendee has chosen not to share their contact number for direct communication.',
						);
					}
				  } else {
					$_rs_array[] = array(
						'attendeeID' => intval($row['id']),
						'chatID' => intval($row['id']),
						'eventID' => intval($event_id),
						'name'=> htmlspecialchars_decode (trim(str_replace(array("Mr.", "Mr", "Miss", "Miss."), "", $row['billing_name'])), ENT_QUOTES),
						'designation'=>htmlspecialchars_decode($row['job_title'], ENT_QUOTES),
						'company'=> htmlspecialchars_decode($row['company'], ENT_QUOTES),
						'email'=>strtolower($row['email']),
						'phoneno'=>$row['isd_code'].$row['phoneno'],
						'linkdInUrl'=>$row['linkedin'],
						'addedOn' => $row['lastVisitiedOn'],						
						'flag'=> "https://www.steelmint.com/steeladmin/flags/" . strtolower($row['flag']) . ".png",
						'country'=>$row['country'],
						'thumbImgSmall'=>$image,
						'thumbImgLarge'=> $image,
						'isBookmarked'=>in_array($row['id'],$bookmark_array)?"Y":"N",
						'textBody'=>"Dear ".trim($row['billing_name']).", this is ".$mem_name.", ".$mem_designation." at ".$mem_company.". With references to SteelMint ".$event_name.", I look forward to having a discussion with you. If this interests you, please reach out to me on " .$emailid." or ". $phonenumber.". Regards",
						'share_contact'=>$share_contact,
						'opt_out_text'=> 'This attendee has chosen not to share their contact number for direct communication.',
					);
			}	
           
        }
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $_rs_array;
	}
	
	public static function getQrDetails($qid=''){
        $result = array();
        //include_once "/home/steelmin/public_html/inc/config1.php";
       /*  $sql ="Select d.`id` AS `contactID`, `name`, `profile_pic` as image,`designation`,`company`,`linkedin` AS `linkedIn`,`email` AS `emailId`,`remarks`, UNIX_TIMESTAMP(`date`) AS `timestamp`, `phoneno` AS `phoneNumber` from tbl_members d left join tbl_country c ON d.country=c.id where 1=1" ; */
	   
	  $sql = "
			SELECT m.`id` AS `contactID`,
				   `profile_pic` AS image,
				   (select name from tbl_designation where id = m.`designation`) as designation,
				   `company`,
				   `linkedin` AS `linkedIn`,
				   `remarks`,
				   c.country_code,
				   UNIX_TIMESTAMP(`date`) AS `timestamp`,
				   m.isd_code
	   ";
            $sql .= ", CASE";
            $sql .= " WHEN m.billing_name = '' THEN m.name";
            $sql .= " ELSE m.billing_name";
            $sql .= " END as name";
            $sql .= ", CASE";
            $sql .= " WHEN m.`send_email_to` = 'R' THEN m.`email`";
            $sql .= " ELSE m.`addtnl_email`";
            $sql .= " END as emailId";
            $sql .= ", CASE";
            $sql .= " WHEN m.`send_email_to` = 'R' THEN m.`phoneno`";
            $sql .= " ELSE m.`alternate_mob_no`";
			$sql .= " END as phoneNumber";
			$sql .= " FROM tbl_members m
						LEFT JOIN tbl_country c ON m.country=c.id
						WHERE 1=1";	   
	   
	   
           $sql .= " and m.`id`={$qid}";
        //echo $sql;
        $rs = mysql_query($sql) or die(mysql_error().$sql);
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
              $row['contactID'] = intval($row['contactID']);
              $row['phoneNumber'] = "+" . $row['isd_code'] . "-" . $row['phoneNumber'];
              $row['flag'] =  "https://www.steelmint.com/steeladmin/flags/" . strtolower($row['country_code']) . ".png";
              $result = $row;   
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $result;

    }

    public static function saveQrDetails($user_id='',$v=array()){
        	$file = fopen("/home/steelmin/public_html/api/pre_function/test.txt", "a");
            fwrite($file, "\n");
            fwrite($file, "\n");
            fwrite($file, json_encode($v));
            fwrite($file, "\n");
            fwrite($file, $user_id);
            fwrite($file, "\ndone\n" );
            fclose($file);
        //include_once "/home/steelmin/public_html/inc/config1.php";
        $existingContactIds = array();
        $event_id = $v["eventID"];
        $whereEventID = '';
        if($event_id == 0 || $event_id != 0)
           $whereEventID = " and event_id = " . $event_id;
            
        if(isset($v["ID"]) && $v["ID"] != null) {
            $createdAt = date('Y-m-d H:i:s');
             //$sql = "SELECT DISTINCT(`contact_id`) FROM `tbl_sm_events_QRcode_contacts` WHERE `memid` = " . $user_id . " AND `event_id` = " . $event_id . " AND `contact_id` = {$v["ID"]} ";
            $sql = "SELECT DISTINCT(`contact_id`) FROM `tbl_sm_events_QRcode_contacts` WHERE `memid` = " . $user_id . "  $whereEventID AND `contact_id` = {$v["ID"]} ";
            $existingContactIdResult = mysql_query($sql);
            if($existingContactIdResult) {
                foreach($existingContactIdResult as $existingContactId) {
                    $existingContactIds[] = $existingContactId['contact_id'];
                }
            }
            //print_r($existingContactIds);
            if(!in_array($v["ID"], $existingContactIds)){
                    $remark = $v["remark"];$member_id = $v["ID"];
                    $sql = "INSERT INTO `tbl_sm_events_QRcode_contacts` (`memid`, `event_id`, `contact_id`, `pRemarks`, `created_at`) VALUES ('" . $user_id . "', '" . $event_id . "', '" . $member_id . "', '" . $remark . "', '" . $createdAt . "')";
                    if(mysql_query($sql)){
						//include_once "/home/steelmin/public_html/inc/desconfig.php";
                       return array("ID"=>$member_id,"eventID"=>$event_id !=''?$event_id:0);
                        
                    }
            } else {
				       //include_once "/home/steelmin/public_html/inc/desconfig.php";
                       return array("ID"=>$v["ID"],"eventID"=>$event_id !=''?$event_id:0);
            }

        }
    }

	public static function qrGen($json_text){
        require('../../phpqrcode/phpqrcode.php');
        $json = json_decode($json_text, true); // decode the JSON into an associative array
        foreach($json as $json_arr){
            $memid= $json_arr['contactID'];
            $json_val= json_encode($json_arr);
            $tempDir = "/home/steelmin/public_html/memidQRCodes/"; //the folder where qr image will store
            $fileName = $memid.'.png'; //qr image name
            $pngAbsoluteFilePath = $tempDir.$fileName;
            //$time_start = microtime(true);
            QRcode::png($json_val, $pngAbsoluteFilePath); //generates QR code (img)
            /*$time_end = microtime(true);
            $time = $time_end - $time_start;
            echo "Did nothing in $time seconds\n";*/
            $arr_res=$pngAbsoluteFilePath; //Path where file is stored in returned
           
     }
     return $arr_res;
    }

    public static function getEventsRowSet($bookmark ='',$is_bookmark=0, $filter=array(), $source='',$registering_id=''){
        //include_once "/home/steelmin/public_html/inc/config1.php";
		$result = array();
		$whereCond = '';$order = "ASC";$limit = "";
		if(isset($filter["eventID"]) && $filter["eventID"] != null){
			$whereCond = " AND e.id =   " . $filter["eventID"];
		}
		if(isset($filter["itemID"]) && $filter["itemID"] != null){
			$whereCond = " AND e.id =   " . $filter["itemID"];
		}
		if(isset($filter["regionID"]) && $filter["regionID"] != null){
			$whereCond .= " AND e.regionID =   " . $filter["regionID"];
		}
		if(isset($filter["commodityID"]) && $filter["commodityID"] != null){
			$whereCond .= " AND e.commodityID =   " . $filter["commodityID"];
		}
		if(!empty($source) && $source != '' ){
			$whereCond .= " AND e.status = 1 " ;
			$order = "ASC ";$limit = " LIMIT 0,5";
		}
		if(isset($filter["source"]) && $filter["source"] == 'home_new'){
			$whereCond .= " AND e.status = 1 " ;
		}
		
          $sql = "SELECT e.`id` AS `eventID`,
		 past_event_video,
       `event_description` AS `objective`,
       `event_type` AS `typeOfEvent`,
       `event_name` AS `title`,
       `event_start_date`,
       `event_end_date`,
       timeLineText,
       `event_name` AS `headingName` ,
       `event_start_date` AS `timeStamp`,
       `event_venue` AS `venueShort`,
       `event_venue` AS `venueFull`,
       `event_image` AS `image`,
       `event_banner_image_1`,
       `event_banner_image_2`,
       `event_banner_image_3`,
       `event_video`,
       (
			SELECT 	`concatenated_name` 
			FROM 	`tbl_state_city` 
			WHERE 	`city_id` = e.`cityID` 
			and 	`state_id` = e.`state` 
			and 	`country_id` = e.`country`
		) as delimitedLocation,
       CASE
           WHEN `status` = 0 THEN 'N'
           WHEN `status` = 1 THEN 'Y'
       END AS `isActive`,
       CASE
           WHEN `isFeatured` = 0 THEN 'N'
           WHEN `isFeatured` = 1 THEN 'Y'
       END AS `isFeatured`,
       `floor_plan_img`,
       `floor_plan_web_url`,
       `website`,
       `event_organizer` AS `eventOrganizer`,
       `agenda` as objective,
	   agenda_new as agenda,  
       e.`agendaPdf`,
       s.`latitude`,
       s.`longitude`
FROM tbl_sm_events_events e
LEFT JOIN tbl_state_city s ON e.cityID = s.id
WHERE 1=1 AND status!=4 $whereCond
ORDER BY event_start_date $order $limit";
		
		$bookmark_array = explode(",",$bookmark);
		$is_bookmarked = $is_bookmark;
		
        $rs = mysql_query($sql) or die(mysql_error().$sql);
        $events_attended_array = array();
        $events_attended = "select DISTINCT(eventid) from final_status where (closed = 'Y' or complementary = 'Y') and participant_type not in ('media') AND registering_id = '{$registering_id}'
        UNION
        select DISTINCT(event_id) from tbl_sm_events_payment_details where inv_no<>'' AND FIND_IN_SET({$registering_id},delegates_ids)";
        $event_sql = mysql_query($events_attended);
        while($row = mysql_fetch_array($event_sql,MYSQL_ASSOC)){
			if($row["eventid"] == 84 || $row["eventid"] == 85 || $row["eventid"] == 86){
				$events_attended_array[] = 84;
				$events_attended_array[] = 85;
				$events_attended_array[] = 86;
			}else{
				$events_attended_array[] = $row["eventid"];
			}
        }
         
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){  
            $banners = array();
            /* $sql_banners = "Select `f_URL` AS `url`, `f_type` AS `type`, `f_thumbnail` AS `thumbImage` from tbl_event_banners where event_id = {$row["eventID"]}";
            $sb = mysql_query($sql_banners);
            while($sb_row = mysql_fetch_array($sb,MYSQL_ASSOC)){
                $banners[] = $sb_row;
            } */
			
			$cntOfBannerImages = 0;
			if(!empty($row["event_banner_image_1"])){
				$banners[] = array("url"=>"https://www.steelmint.com/steeladmin/event-admin/images/{$row['event_banner_image_1']}","type"=>"image","thumbImage"=>"https://www.steelmint.com/steeladmin/event-admin/images/{$row['event_banner_image_1']}");
				$cntOfBannerImages += 1;
			}	
			 if(!empty($row["event_banner_image_2"])){
				$banners[] = array("url"=>"https://www.steelmint.com/steeladmin/event-admin/images/{$row['event_banner_image_2']}","type"=>"image","thumbImage"=>"https://www.steelmint.com/steeladmin/event-admin/images/{$row['event_banner_image_2']}");
				$cntOfBannerImages += 1;
			}	
			 if(!empty($row["event_banner_image_3"])){
				$banners[] = array("url"=>"https://www.steelmint.com/steeladmin/event-admin/images/{$row['event_banner_image_3']}","type"=>"image","thumbImage"=>"https://www.steelmint.com/steeladmin/event-admin/images/{$row['event_banner_image_3']}");
				$cntOfBannerImages += 1;
			}	
						if($source == "home"){							
						//$row["image"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", "https://www.steelmint.com/sm_group_events/images/events/{$row["image"]}") . "?tr=h-290,w-230";
						$row["image"] = "https://www.steelmint.com/sm_group_events/images/events/{$row["image"]}" . "?tr=h-290,w-230";
				$row["image"] = str_replace(basename($row["image"]),"thumb_".basename($row["image"]),$row["image"]);
			}	
				//$row["image"] = $row["image"] != ''?"https://www.steelmint.com/sm_group_events/images/events/{$row["image"]}":$row["image"];			
			else				$row["image"] = $row["image"] != ''?"https://www.steelmint.com/sm_group_events/images/events/{$row["image"]}":$row["image"];			
			if( $cntOfBannerImages == 0 )
				$banners[] = array(
									"url"			=>	$row["image"],
									"type"			=>	"image",
									"thumbImage"	=>	$row["image"]
								);
			
			 if(!empty($row["event_video"])){
				 $exp_v = explode("=",$row["event_video"]);
				 $exp_b = explode("/",$row["event_video"]);
				 $lk = count($exp_b);
				 $banners[] = array("url"=>$row['event_video'],"type"=>"video","thumbImage"=>$exp_v[1] != ""?"https://i.ytimg.com/vi/{$exp_v[1]}/hqdefault.jpg":"https://i.ytimg.com/vi/{$exp_b[$lk-1]}/hqdefault.jpg");
			 }			
			 
            $speakers = array();
            $sql_speaker = "Select es.`name` , CONCAT('https://www.steelmint.com/sm_group_events/images/events/speakers/',es.`image`) AS `thumbImg` from tbl_sm_events_speakers es LEFT JOIN tbl_sm_event_to_speaker ets ON es.`id` = ets.`speaker_id` where ets.`event_id`={$row['eventID']} order by es.`id` ASC";
			$sk = mysql_query($sql_speaker); $c=1;
			$speakers["first"]=array("name"=>"","thumbImg"=>"");$speakers["second"]=array("name"=>"","thumbImg"=>"");
            while($spk_row = mysql_fetch_array($sk,MYSQL_ASSOC)){
                  $spk_row["name"] = removeMSWordattributes(html_entity_decode($spk_row["name"], ENT_QUOTES));
				  if($c == 1){
                    $speakers["first"] = $spk_row;
                  } else if($c == 2){
                    $speakers["second"] = $spk_row;
                  }
                  $c++;
            }
			$speakers["count"] = $c>2?$c-2-1:0;
			
            $row["floorPlan"] = array("imgUrl"=>$row['floor_plan_img'],"webUrl"=>$row['floor_plan_web_url']);
            if( $row["eventID"] == 33 || $row["eventID"] == 53 || $row["typeOfEvent"] == "Webinar" )
				$row["iAttended"] = "Y";
			else
				$row["iAttended"] = in_array($row["eventID"], $events_attended_array) ? "Y":"N";
            $row["banner"] = $banners;
			$row["speaker"] = $speakers;
			unset($row['floor_plan_img']);unset($row['floor_plan_web_url']);
            $attendees = array();
           $sql_attendee = "				Select 	d.`name` , 						CONCAT('https://www.steelmint.com/images/clients/',d.`profile_pic`) AS `thumbImg` 				FROM 	tbl_members d 				LEFT JOIN final_status sa ON d.id=sa.registering_id 				WHERE 	sa.eventid={$row['eventID']} 				AND		(sa.closed = 'Y' OR sa.complementary = 'Y')				ORDER BY d.id ASC			";
			$atn = mysql_query($sql_attendee); $c=1;
			$attendees["first"]=array("name"=>"","thumbImg"=>"");$attendees["second"]=array("name"=>"","thumbImg"=>"");
            while($atn_row = mysql_fetch_array($atn,MYSQL_ASSOC)){
                  if($c == 1){
                    $attendees["first"] = $atn_row;
                  } else if($c == 2){
                    $attendees["second"] = $atn_row;
                  }
                  $c++;
            }
			$attendees["count"] = $c>2?$c-2-1:0;
			$row["eventID"] = intval($row["eventID"]);
			$vtime = strtotime($row["timeStamp"]);
			$row["timeStamp"] = "{$vtime}";
			$row["displayDate"] = date("j M y", strtotime($row["event_start_date"])). " - ".date("j M y", strtotime($row["event_end_date"]));
			$row["objective"] = removeMSWordattributes(html_entity_decode($row["objective"], ENT_QUOTES));
			$row["title"] = removeMSWordattributes(html_entity_decode($row["title"], ENT_QUOTES));
			$row["timeLineText"] = $row["timeLineText"];
			$row["headingName"] = removeMSWordattributes(html_entity_decode($row["headingName"], ENT_QUOTES));
			//$row["agenda"] = utf8_decode($row["agenda"]);
			$row["agenda"] = $row["agendaPdf"];
			
            $row["attendee"] = $attendees;
			$row["isBookmarked"] = in_array($row["eventID"],$bookmark_array)?"Y":"N";
			$row["latitude"] = (double) $row["latitude"];
			$row["longitude"] = (double) $row["longitude"];
			$row["past_event_video"] = $row["past_event_video"];
			
			if($is_bookmarked){
				if(in_array($row["eventID"],$bookmark_array)){
					$result[] = $row;
				}
			} else {
				$result[] = $row;
			}
			
            //print_r($row);
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
       return $result;
	}
	
	public static function getEventsWebRowSet($bookmark ='',$filter= array(),$l,$is_bookmarked=0,$offset=0,$page=0, $source){
		  //echo "M";
		  //include_once "/home/steelmin/public_html/inc/config1.php";
		$cond="";$archived=array();$upcoming=array();
		if(isset($filter['commodityID']) && $filter['commodityID'] !=''){
		    $commId = implode(",", $filter['commodityID']);
		   $cond .= " and `commodityID` IN ($commId) ";
		}
	    //tbl_events.regionID = countryID
        //tbl_events.cityID  = tbl_state_city.id -> used to get lat, long
		   //print_r ($filter);
		if(isset($filter['regionID']) && $filter['regionID'] !=''){
		    
			if($source == "mapView" || $source == "mapview"){
			    
			   $continents = $filter['regionID'];
			    $regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID in ($continents) OR id  in ($continents)) ");
			} else {
    			$regions = $filter['regionID'];
			}		    
		    
		   $cond .= " and `regionID` IN ($regions)";   
		}  

		
		   
		if(isset($filter['year']) && $filter['year'] !='')
		   $cond .= " and `start_date` like '%{$filter['year']}-%'"; 
		   
		$cur_time = date('Y-m-d');  
		if($is_bookmarked == 0 && strtolower($source) != 'mapview'){ //normal listing
			if($l == "upcoming")
		    	$cond .= " and `end_date` >= '$cur_time' ";
			
			if($l == "archived")
			    $cond .= " and `end_date` < '$cur_time' ";   
		} else //list of bookmarked items/mapview
		    $cond .= " and `end_date` >= '$cur_time' ";
		$result = array();
        //$sql = "Select e.`id` AS `eventID`, `details` AS `eventInformation`,`title`,`start_date` AS `eventDate`,`venue` AS `eventLocation`, CONCAT('https://www.steelmint.com/images/evnts/',`img_name`) AS `imgurl`,`website`,`organiser` AS `eventOrganizedBy`,CONCAT('https://www.steelmint.com/dnldFiles.php?path=impNotices&download_file=',`pdf_file`) AS `brochureUrl`, `end_date`, sc.`latitude`,sc.`longitude` from tbl_events e left join tbl_state_city sc on e.cityID = sc.id where 1=1 {$cond} order by `end_date` DESC LIMIT {$offset}, 8";
        $sql = "
			Select 	e.`id` AS `eventID`, 
			         sc.country_id as regionID,
					`details` AS `eventInformation`,
					`title`,
					`start_date` AS `eventDate`,
					`venue` AS `eventLocation`, 
					CONCAT('https://www.steelmint.com/images/evnts/',`img_name`) AS `imgurl`,`website`,`organiser` AS `eventOrganizedBy`,
					CONCAT('https://www.steelmint.com/dnldFiles.php?path=impNotices&download_file=',`pdf_file`) AS `brochureUrl`, `end_date`, 
					sc.`latitude`,
					sc.`longitude`,
					(select itemName from tbl_region_commodity_master where itemType = 'commodity' and id = e.commodityID) as 'commodityName'
			from tbl_events e 
			left join tbl_state_city sc on e.cityID = sc.id where 1=1 {$cond} 
			order by `end_date` DESC 
			LIMIT {$offset}, 8
	    ";
	
	
		$bookmark_array = explode(",",$bookmark);
        $rs = mysql_query($sql) or die(mysql_error().$sql);
         
        while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){  
			$row["eventID"] = intval($row["eventID"]);
			//$vtime = strtotime($row["end_date"]);
			$row["eventInformation"] = removeMSWordattributes(html_entity_decode($row["eventInformation"], ENT_QUOTES));
			$row["title"] = removeMSWordattributes(html_entity_decode($row["title"], ENT_QUOTES));
			$row["isBookmarked"] = in_array($row["eventID"],$bookmark_array)?"Y":"N";
			$row["latitude"] = doubleval($row["latitude"]);
			$row["longitude"] = doubleval($row["longitude"]);
         
			
			
			if($is_bookmarked){
				if(in_array($row["eventID"],$bookmark_array)){
        		
					$result[] = $row;
				}
			} else {
				 
					$result[] = $row;	
			}
		
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
       return $result;

	}
	
	//Function for Half Cooked News API
	//Yashwant 05 Dec'22
	public static function getNewsRowWidgetAPI($pageCount=0,$commodityFilter='',$api_key='')
	{
        $result=array();
		$offset = $pageCount*20;
		$sql = "SELECT a.`post_title`,";		
		$sql .= "	a.`href`,a.`image`,a.`post_date`,a.`post_time`,a.`f_excerpt`,a.`commodityId` FROM `tbl_news_post` a where 1";
		
		if($api_key == "2Hjolp4XZ3Nw8OmnNlr6")
			$sql .= " and for_smgroup_company like '%coalmint%'";
		
		if($api_key == "HgyTR8pQwL1mnz5Xo93K")
			$sql .= " and commodityId in (403,413)";
		
		if($commodityFilter!='')
			$sql .= " and (commodityId in ($commodityFilter) or subCommodityId in ($commodityFilter) or subSubCommodityID in ($commodityFilter))";
		
		$sql.= " order by id desc";
		$sql .= " LIMIT " . (int)$offset . ", 20";
		// echo $sql;
		// die;
		$query = mysql_query($sql);
		while($row = mysql_fetch_assoc($query)){
			$title = removeMSWordattributes(html_entity_decode( stripslashes($row['post_title']), ENT_QUOTES));
			$result['Title'] = $title;
			$row['f_excerpt'] = str_replace(array("&amp;#8217;","&amp;#8216;","&amp;hellip;"), "&#039;", $row['f_excerpt']);
			$row['f_excerpt'] = str_replace(array("#8217;","#8216;"), "&#039;", $row['f_excerpt']);

            //comvert - of MS word
			$row['f_excerpt'] = str_replace(array("&amp;#8211;","&amp;#8212;"), "-", $row['f_excerpt']);
			$row['f_excerpt'] = str_replace(array("#8211;", "#8212;"), "-", $row['f_excerpt']);			

            //comvert doublequotes of MS word
			$row['f_excerpt'] = str_replace(array("&amp;#8220;","&amp;#8221;"), "&#34;", $row['f_excerpt']);
			$row['f_excerpt'] = str_replace(array("#8220;", "#8221;"), "&#34;", $row['f_excerpt']);
			$content = removeMSWordattributes(html_entity_decode(stripslashes($row['f_excerpt']), ENT_QUOTES));
			$content = substr($content, 0, 125);
			$result['Description'] = $content;
			$result['Image'] = $row['image'];
			$url_parts = parse_url($row['href']);
			
// 			if(isset($url_parts['path']) && ($row['commodityId']==401)) {
// 				$href = "https://www.coalmint.com/". rtrim(ltrim($url_parts['path'], '/'), '/');
// 			}else{
				$href = $row['href'];
			//}
			$href = str_replace("https://www.steelmint.com/insights/", config('constants.siteUrl')."insights/detail/", $href);
			$result['URL'] = $href;
			$result['Date'] = $row['post_date']." ".$row['post_time'];
			$data[]=$result;
		}
		return $data;
    }
	
	//Function for Lohaa News
	//Yashwant Kumar Vaid 31 Aug'23
	public static function getLohaaNews()
	{
        $data = array(); // Initialize the main data array

		$conditions = array(
			array("key" => "subCommodityId", "value" => 439, "limit" => 3),
			array("key" => "commodityId", "value" => 403, "limit" => 1),
			array("key" => "subCommodityId", "value" => 973, "limit" => 1)
		);

		foreach ($conditions as $condition) {
			$sql = "SELECT a.`post_title`, a.`href`, a.`image`, a.`post_date`, a.`post_time`, a.`post_content`
					FROM `tbl_news_post` a
					WHERE {$condition['key']} = {$condition['value']} AND DATE(a.`post_date`) = '".date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -1 days'))."'";
			$sql .= "ORDER BY id DESC
					LIMIT {$condition['limit']}";
			// echo $sql;
			// echo "<br>";
			$query = mysql_query($sql);
			
			while ($row = mysql_fetch_assoc($query)) {
				$result = array(); // Initialize a new result array for each iteration
				
				$title = removeMSWordattributes(html_entity_decode(stripslashes($row['post_title']), ENT_QUOTES));
				$result['Title'] = $title;
				
				// Similar content processing as before
				$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
				$result['Description'] = $content;
				$result['Image'] = $row['image'];
				
				$data[] = $result;
			}
		}
		return $data;
    }
	
	//get Insights
	//DEFAULT_NEWS_LIMIT
	public static function getInsightsRows($memid=0, $source='listing', $resourceType="app", $type='default', $filter=array(), $pageType='post', $limit=5, $offset=0, $appType='SM'){
		//include_once "/home/steelmin/public_html/inc/config1.php"; 
        $result=array(); 
        $news = array();
		
		$_post_ids='';$isPagination=true;
		$sourceNew = '';
		if(strtolower($filter['sourceNew'])=='commoditywise' || strtolower($filter['sourceNew'])=='regionwise' ){
            $sourceNew =strtolower($filter['sourceNew']);
		}
		if((strtolower($source)=='commoditywise' || strtolower($source)=='regionwise' || strtolower($source)=='regioncommoditywise') && $offset==0){
			$source='listing';
		}elseif((strtolower($source)=='commoditywise' || strtolower($source)=='regionwise' || strtolower($source)=='regioncommoditywise') && $offset==0){
			if(isset($filter['debug']) && $filter['debug'] == 1) {
				echo "line 1816-".strtolower($source);
			}
			$source='listing';
			$cw = 0; $c_ids = '';
			$rw = 0; $r_ids = '';
			if(strtolower($source)=='regionwise'){
				$rw = 1;
				$r_ids = " n.showInRegionWise = 1 and n.`continentID` = " . implode("," , $filter['regionID']);
				
				/* $continents = implode("," , $filter['regionID']);
			    $regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID = " . $continents . " OR id  = " . $continents . ") ");
				
				if( $regions=='')
					 $regions=0;
				$sql = "select cityID, group_concat(`post_id` order by `post_id` desc) as ids from tbl_news_post as n left outer join tbl_state_city sc ON sc.ID = n.cityID where sc.`country_id` IN ($regions) and commodityId<>0  and for_smgroup_company like '%steelmint%' group by cityID  order BY post_id desc"; */
			}elseif(strtolower($source)=='commoditywise'){
				//$sql = "select `subCommodityId`, group_concat(`post_id` order by `post_id` desc) as ids from tbl_news_post where `commodityID` = " . implode("," , $filter['commodityID']) . "  and for_smgroup_company like '%steelmint%' group by subCommodityId order BY post_id desc";
				$cw = 1;
				$c_ids = " n.showInCommodityWise = 1 and n.`commodityID` = " . implode("," , $filter['commodityID']);
			}elseif(strtolower($source)=='regioncommoditywise'){
				
				$continents = implode("," , $filter['regionID']);
				$continents1 = implode("," , $filter['commodityID']);
				if($continents == '' && $continents1  == ''	){
					$cw = 1;
					$c_ids = " n.showInCommodityWise = 1 ";
					//$sql = "select `subCommodityId`, group_concat(`post_id` order by `post_id` desc) as ids from tbl_news_post where 1 and for_smgroup_company like '%steelmint%' group by subCommodityId order BY post_id desc";
				} elseif($continents <> '' && $continents1 <> ''){
					$cw = 1;
					$c_ids = " ((n.showInRegionWise = 1 and n.`continentID` = " . $continents;
					$c_ids .= ") AND (n.showInCommodityWise = 1 and n.`commodityID` = " . $continents1 . ")) ";
					
/* 					$regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID = " . $continents . " OR id  = " . $continents . ") ");
					
					$sql = "select cityID, group_concat(`post_id` order by `post_id` desc) as ids from tbl_news_post as n left outer join tbl_state_city sc ON sc.ID = n.cityID where sc.`country_id` IN ($regions) and commodityId in ($continents1) and for_smgroup_company like '%steelmint%' group by cityID, subCommodityId  order BY post_id desc";
 */				}elseif($continents <> '' && $continents1  == ''){
					$cw = 1;
					$c_ids = " n.showInRegionWise = 1 and n.`continentID` = " . $continents;
	 
/* 					$regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID = " . $continents . " OR id  = " . $continents . ") ");
					if( $regions=='')
						$regions=0;
				 
					$sql = "select cityID, group_concat(`post_id` order by `post_id` desc) as ids from tbl_news_post as n left outer join tbl_state_city sc ON sc.ID = n.cityID where sc.`country_id` IN ($regions) and for_smgroup_company like '%steelmint%' group by cityID, subCommodityId  order BY post_id desc"; */
				}elseif($continents1 <> '' && $continents  == ''){
					$cw = 1;
					$c_ids = " n.showInCommodityWise = 1 and n.`commodityID` = " . implode("," , $filter['commodityID']);
//						$sql = "select `subCommodityId`, group_concat(`post_id` order by `post_id` desc) as ids from tbl_news_post where `commodityID` = " . implode("," , $filter['commodityID']) . "  and for_smgroup_company like '%steelmint%' group by subCommodityId order BY post_id desc";
				}
			}
			//$sqlBD = "SET SESSION group_concat_max_len = 100";
			//mysql_query($sqlBD) or die(mysql_error().$sqlBD);
			if(isset($filter['debug']) && $filter['debug'] == 1) {
				echo "line 1869-".$cw.'--'.$rw;
			}
			if( $cw == 0 & $rw == 0){
				$res = mysql_query($sql) or die(mysql_error().$sql);
				while($row = mysql_fetch_assoc($res,MYSQL_ASSOC))
				{
					$resArr = explode(',', $row['ids']);
					$input_array = array_chunk($resArr, DEFAULT_NEWS_LIMIT);
					if(isset($input_array[0])){
						if($_post_ids)
							$_post_ids.=',';
						$_post_ids.=implode(',',$input_array[0]);
					}
				}
			}			
		}
		///and appType ='$appType'
		// and resourceType='$resourceType' removed ad as we are saving single entry irrespective of web/app (resourceType='$resourceType')
		$sql = "SELECT n.*,sc.latitude, sc.longitude, sc.country_id as regionID,
				(select itemName from tbl_region_commodity_master as cm where n.subCommodityId=cm.id and itemType='commodity') as commodityName,
				(select itemName from tbl_region_commodity_master as cm where sc.country_id=cm.id and itemType='region') as regionName,
				(select id from tbl_bookmarks as b where n.post_id=b.item_id and b.memid=$memid and section like 'insight%'  and status='active'  limit 1) as isBookmarked, 
				n.author_name  as author_name, n.author_id  as author_id, n.author as author_email, rm.imageURL as author_imageURL, rm.facebookId as author_facebookId, rm.twitterId as author_twitterId, rm.linkedIn as author_linkedIn 
				,(select action from tbl_show_more_less_like as c where n.post_id=c.item_id and memid=$memid and section='insight' limit 1) as showMoreOrLess
				FROM `tbl_news_post` n 
				left outer join tbl_rel_manager rm ON rm.RM_email = n.author
				left outer join tbl_state_city sc ON sc.ID = n.cityID
				";
		$sql .= " WHERE n.`id` > 0 ";
		if($_post_ids != ''){//
			$sql .= " and n.`post_id` IN ($_post_ids) ";
			$isPagination=false;
		} elseif( $cw == 1) {
			$sql .= " and " . $c_ids;
			$isPagination=false;
		} elseif( $rw == 1) {
			$sql .= " and " . $r_ids;
			$isPagination=false;
		}
		if(isset($filter['isNFS']) && $filter['isNFS']=='Y'){
			$sql.=" and n.category='NON FERROUS' ";
		}
		$orderBY = "";

		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<br /><br /><pre>1st sql:", $sql, "</pre>";
				
        } 		
		
		if($source!='') {//source
			
			switch($source){				
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark':
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
					/* $bookMarkedIds = qryToCommaSepString("select lead_id from tbl_bookmark as b where  user_id=$memid and section='news' and appType ='$appType' ");
					if($bookMarkedIds)
						$filter['itemID'] = explode(',', $bookMarkedIds);
					else
						$filter['itemID'] = 0; */
					$common = new Common();
					$bookMarkedIds = $common->getUserBookmarksV2019($resourceType, $memid, $section='insight', $status='', $event_id=0);
					//$filter['itemID'] = explode(',', $bookMarkedIds);
					if(count($bookMarkedIds)>0)
						$filter['itemID'] = $bookMarkedIds;
					else
						$filter['itemID'] = array(0);
				break;
				case 'portfolio':
                   /*  $common = new Common();
					$temp = $common->getUserPortfolioV2019($memid, 'news', $appType);		
					print_r($temp); */
					//and appType='".$appType."'
					$sqlTC = "select regionId, commodityID from tbl_user_portfolio where user_id=".$memid." and type='intel_insight' and appType='$appType'  order by id desc limit 1"; 
					$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
					$temp = mysql_fetch_array($rsTC,MYSQL_ASSOC);					
					
					if($temp['commodityID']){
						$commodityIDs = $temp['commodityID'];
						$filter['commodityID'] = explode(',',$commodityIDs);
					}
					if($temp['regionId']){
						$regionIDs = $temp['regionId'];
						$filter['regionID'] = explode(',',$regionIDs);
					}
					
					if(empty($filter['commodityID']) && empty($filter['regionID'])){
						return $result;
					}
					//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'relatedinsights':
				case 'relatedInsights':
					if($filter['relatedSection']=='price'){
						$sqlTC = "select subCommodityID, sc.`country_id` as regionID
								from tbl_price_static as n
								left join tbl_state_city sc
								ON sc.ID = n.cityID
								where  relation_id  = '".$filter['relatedItemID']."'
							";
					}else{
						$sqlTC = "select subCommodityID, sc.`country_id` as regionID
								from tbl_news_post as n
								left join tbl_state_city sc
								ON sc.ID = n.cityID
								where  post_id  = '".$filter['relatedItemID']."'
							";
					}
					//echo $sqlTC;die;
					$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC); 	
					$cr_data = mysql_fetch_assoc($rsTC);
					//print_r($cr_data);
					if(empty($cr_data)){
						$source= 'home';
					}else{
						$filter['commodityID'][] = $cr_data["subCommodityID"]; 
						$filter['regionID'][] = $cr_data["regionID"]; 
												
						$source= '';						
					}
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'commodity':
				case 'commoditywise':
				case 'commodityWise':
					if( $resourceType=="app" )
					    $orderBY = " n.post_date Desc, n.post_time Desc";
					else  { 
					    //$orderBY = " n.commodityID, n.SubCommodityID, n.post_date Desc, n.post_time Desc";
					    $orderBY = "  n.post_date Desc, n.post_time Desc";
					}
				break;
				case 'region':
				case 'regionwise':
				case 'regionWise':
					if( implode("," , $filter['regionID']) == 113 || implode("," , $filter['regionID']) == 49  )
						$orderBY = " post_date Desc, post_time Desc ";
					else{
					    if( $resourceType=="app" )
						    $orderBY = " n.post_date Desc, n.post_time Desc ";
						else    
						    $orderBY = " n.continentID,n.post_date Desc, n.post_time Desc ";
					}	
				break;
				case 'recent':
				case 'latest':
    			    /*$item = array();
    				$sqlTC = "select `item_id` from tbl_recently_viewd where memid=".$memid." order by id desc limit 10"; 
    				$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
    				while($temp = mysql_fetch_array($rsTC,MYSQL_ASSOC)){
    					$item[]= $temp['item_id'];
    				}
    				///$filter['itemID'] = implode(",",$item);
    					if(count($item)>0)
    						$filter['itemID'] = $item;
    					else
    						$filter['itemID'] = array(0);
                        //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
                    */
                    $orderBY = " post_date Desc, post_time Desc ";
				break;
				default: //like listing , mapview and others
					//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
					if( isset($filter['sliderID']) ){
						
						if($filter['sliderID']!=''){
							$common = new Common();
							
							$sliderRes = $common->getSliderDetails($filter['sliderID']);
							
							if(empty($sliderRes)){								
								$filter['commodityID'] = array(); 
								$filter['regionID'] = array();
							}else{
								if($sliderRes['commodityID'])
									$filter['commodityID'] = array($sliderRes['commodityID']); 
								if($sliderRes['regionID'])
									$filter['regionID'] = array($sliderRes['regionID']); 
							}
							
						}else{							
							$filter['commodityID'] = array(); 
							$filter['regionID'] = array();								
						}
					}
					
					$orderBY = " post_date Desc, post_time Desc ";
				break;
			}			
		}
		
		if(isset($filter['relatedItemID']) && !empty($filter['relatedItemID']) && $filter['relatedSection']=='insight') {
			$sql .= " AND n.`post_id` <> " . (int)$filter['relatedItemID'];
		}
		
		if(isset($filter['searchTerms']) && !empty($filter['searchTerms'])) {
			$cd = date("Y-m-d");
			$ct = date("H:i:s");
			mysql_query("
				insert into tbl_searches 
				values (
				'',
				'$cd',
				'$ct',
				$memid,
				'insight',
				'" . htmlspecialchars($filter['searchTerms'], ENT_QUOTES) . "',
				'$resourceType'
				)"
			);
			$sql .= " AND (";

			$implode = array();

			$words = explode(' ', trim(preg_replace('/\s+/', ' ', $filter['searchTerms'])));
			$words = str_replace(array("insight","insights", "news"), "", $words);
			$words =  preg_replace('/[^A-Za-z0-9\-]/', '', $words); // Removes special chars.
			foreach ($words as $word) {
					$implode[] = ' (n.`indexing` REGEXP "[[:<:]]' . $word . '[[:>:]]")   ';
					//$implode[] = "CONCAT(n.`post_title`, n.`post_content`,n.category,n.sub_category,n.author_name,n.href,n.post_tags,n.region) LIKE '%" . mysql_real_escape_string($word) . "%'";
			}

			if ($implode) {
				$sql .= " " . implode(" AND ", $implode) . "";
			}

			$sql .= ")";
		}   
		
		if(isset($filter['trendingTags']) && !empty($filter['trendingTags'])) {			
			//get trendingTags and pass as like in table tbl_news_post
            $sql .= " AND FIND_IN_SET({$filter['trendingTags']}, n.`trending_tag`) > 0 ";

		}
		$visitHistory=0;
		$visitItemSeen=false;
		if(isset($filter['itemID']) && !empty($filter['itemID'])) {
						if(isset($filter['debug']) && $filter['debug'] == 1) {
				echo "line 2080-";
			}

			if(is_array($filter['itemID']))
				$sql .= " AND n.`post_id` IN (" . implode(',',$filter['itemID']) .")";
			else
				$sql .= " AND n.`post_id` = " . (int)$filter['itemID'];
			
					
			/* $sqlRCMResult = DB::table('tbl_year_week')
				->select('week'.'year')
				->where('sunday', '<=', $GLOBALS['currDate'])
				->orderBy('monday' , 'desc')
			   ->first();
			echo $weekNo = $sqlRCMResult['week'].'-'.$sqlRCMResult['year']; 
			
			$visitor_history_id = isset($filter['visitor_history_id'])?$filter['visitor_history_id']:0;
			$uData = array("section" =>'insight',"item_id"=>(int)$filter['itemID'],"memid"=>$memid,"created_on"=>date('Y-m-d H:i:s'),"resource_type"=>$resourceType,"appType"=>'SM', "weekYear"=>$weekNo, "visitor_history_id"=>$visitor_history_id);
			
			DB::table("tbl_recently_viewd")->insert($uData);
			*/
			if($source=='details'){
				/* $sql_qry = "SELECT concat(week, '-',year) FROM `tbl_year_week` where  sunday >= '". date("Y-m-d", strtotime($GLOBALS['currDate']))."' and monday<='". date("Y-m-d", strtotime($GLOBALS['currDate']))."' ORDER BY `tbl_year_week`.`monday` desc limit 1";
				
				$weekNo = qryToCommaSepString($sql_qry); */
				
				$visitor_history_id = isset($filter['visitor_history_id'])?$filter['visitor_history_id']:0;
				
				
				$user = new User($memid, $appType);
				$isAccessible =  $user->isAccessible($resourceType, $section='Insights','','','',$filter['selected_market']);
				
				/*if($isAccessible==-1 && Session::get('userService') != 'Standard' && Session::get('userService') != 'Corporate Standard'  && Session::get('userService') != 'Price Only' && Session::get('userService') != 'Free Trial'){
					$pageType='post'; 
				}*/
				if($isAccessible==-1 && 
				Session::get($filter['selected_market'])['userService'] != 'Standard' && Session::get($filter['selected_market'])['userService'] != 'Corporate Standard'  && Session::get($filter['selected_market'])['userService'] != 'Price Only' && Session::get($filter['selected_market'])['userService'] != 'Free Trial'){
					$pageType='post'; 
				}elseif(isset($filter['is_blog']) && $filter['is_blog'] != '') {
					$pageType='post'; 
				}else{
					$pageType='pre';
					//weekYear='$weekNo' 
					//and appType='".$appType."'
                    $sqlTC = "
                        select distinct item_id 
                        from tbl_recently_viewd 
                        where created_on >= '".$GLOBALS['currDate']." 00:00:00'
                        and created_on <= '".$GLOBALS['currDate']." 23:59:59'
                        and resource_type='$resourceType' 
                        and section='insight'
					";					
					/*$sqlTC = "
    					select distinct item_id 
    					from tbl_recently_viewd 
    					where STR_TO_DATE(created_on, '%Y-%m-%d') = '".$GLOBALS['currDate']."'
    					and resource_type='$resourceType' 
    					and section='insight' 
					"; */
					if($memid)
						$sqlTC .= " AND memid=".$memid." ";
					elseif($visitor_history_id)
						$sqlTC .= " AND visitor_history_id=".$visitor_history_id." ";
					//AND user_id=".$memid." 
					$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
					$visitHistory = mysql_num_rows($rsTC);		
					
					while($temp = mysql_fetch_array($rsTC,MYSQL_ASSOC)){
						$visitItem[]= $temp['item_id'];
					}
					
					if(in_array($filter['itemID'], $visitItem)!==false){
						$visitItemSeen =  true;
					}
				}
				//echo Session::get('userType');
				
				if(Session::get($filter['selected_market'])['userType']!=1){
				//if(strpos(Session::get('sectionsIncludes'), "Insights") === false){
					$chkVisitHistoryCount = $appType=='CM'?1:2;
					if(($visitItemSeen==true && $pageType=='pre') || ($visitHistory<$chkVisitHistoryCount && $pageType=='pre') || $pageType=='post'){
						$sql_qry = "INSERT INTO `tbl_recently_viewd` (`section`, `item_id`, `memid`, `created_on`, `resource_type`, `appType`, `visitor_history_id`, `weekYear`) VALUES ('insight','" . $filter['itemID'] . "', '" . $memid . "', '" . $GLOBALS['currDateTime'] . "', '" . $resourceType . "', 'SM', '" . $visitor_history_id . "', '" . $weekNo . "')";
						
						 mysql_query($sql_qry) or die(mysql_error());
					}
				}elseif(Session::get($filter['selected_market'])['userService'] == 'Standard'  || Session::get($filter['selected_market'])['userService']== 'Corporate Standard' || Session::get($filter['selected_market'])['userService'] == 'Free Trial'){
					$chkVisitHistoryCount = $appType=='CM'?1:10;
					if(($visitItemSeen==true) || $visitHistory<$chkVisitHistoryCount ){
						$sql_qry = "INSERT INTO `tbl_recently_viewd` (`section`, `item_id`, `memid`, `created_on`, `resource_type`, `appType`, `visitor_history_id`, `weekYear`) VALUES ('insight','" . $filter['itemID'] . "', '" . $memid . "', '" . $GLOBALS['currDateTime'] . "', '" . $resourceType . "', 'SM', '" . $visitor_history_id . "', '" . $weekNo . "')";
						
						mysql_query($sql_qry) or die(mysql_error());
					}
				}elseif(Session::get($filter['selected_market'])['userService'] == 'Price Only' ){
					$chkVisitHistoryCount = $appType=='CM'?1:2;
					if(($visitItemSeen==true) || $visitHistory<$chkVisitHistoryCount ){
						$sql_qry = "INSERT INTO `tbl_recently_viewd` (`section`, `item_id`, `memid`, `created_on`, `resource_type`, `appType`, `visitor_history_id`, `weekYear`) VALUES ('insight','" . $filter['itemID'] . "', '" . $memid . "', '" . $GLOBALS['currDateTime'] . "', '" . $resourceType . "', 'SM', '" . $visitor_history_id . "', '" . $weekNo . "')";
						
						mysql_query($sql_qry) or die(mysql_error());
					}
				}
				if( $resourceType=="web" ){
					$sql_qry = "UPDATE `tbl_news_post` SET `most_read` = (`most_read` + 1) WHERE `post_id` = " . (int)$filter['itemID'];

					mysql_query($sql_qry);
					
					$update =	"UPDATE tbl_intel_insight_hashmap AS to_update
								INNER JOIN tbl_news_post AS update_from
								ON 	to_update.post_id = ".(int)$filter['itemID']."
								AND update_from.post_id = ".(int)$filter['itemID']."		
								SET to_update.most_read = update_from.most_read";
					mysql_query($update);
				}
			}
			
			/*
			///allow already visited item
			$sqlTC = "select weekYear from tbl_recently_viewd 
			where weekYear<>'$weekNo' 
			and item_id= '" . $filter['itemID'] . "'
			and resource_type='$resourceType' 
			and section='insight' 
			and appType='".$appType."'
			"; 
			if($memid)
				$sqlTC .= " AND memid=".$memid." ";
			elseif($visitor_history_id)
				$sqlTC .= " AND visitor_history_id=".$visitor_history_id." ";
			$sqlTC .= " ORDER BY id desc limit 1";
			
			$oldWeekYear = qryToCommaSepString($sqlTC);
			if($oldWeekYear!='' && ($visitor_history_id>0 || $memid>0)){
				$sql_qry = "INSERT INTO `tbl_recently_viewd` (`section`, `item_id`, `memid`, `created_on`, `resource_type`, `appType`, `visitor_history_id`, `weekYear`) VALUES ('insight','" . $filter['itemID'] . "', '" . $memid . "', '" . $GLOBALS['currDateTime'] . "', '" . $resourceType . "', 'SM', '" . $visitor_history_id . "', '" . $oldWeekYear . "')";
				
				$rs_weeks = mysql_query($sql_qry) or die(mysql_error());
			}
			*/
			
		}
		
		if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
		    if(strtolower($source) != "commoditywise" && strtolower($source) != "regioncommoditywise"){
    			$sql .= " AND (";
    				$sql .= " `commodityID` IN (";
    				$sql .= implode(", ", $filter['commodityID']);
    				$sql .= ")";
    				$sql .= " OR ";	
    				$sql .= " `subCommodityId` IN (";
    				$sql .= implode(", ", $filter['commodityID']);
    				$sql .= ")";
    				$sql .= " OR ";	
    				$sql .= " `subsubCommodityID` IN (";
    				$sql .= implode(", ", $filter['commodityID']);
    				$sql .= ")";
    			$sql .= ")";
		    }
		}
		
		if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
			$flag = 0;
			if(strtolower($source) == "mapView" || strtolower($source) == "regionwise"|| strtolower($source) == "regioncommoditywise"){
			    $continents = implode("," , $filter['regionID']);
			    $regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID in ($continents) OR id  in ($continents)) ");
				$flag = 1;
			} else{ //if(strtolower($source)!=='regionwise' && strtolower($source)!=='regioncommoditywise') {
    			$regions = implode(",", $filter['regionID']);
				$flag = 1;
			}
			if($flag == 1){ 
				$sql .= " AND ";
				$sql .= " (sc.`country_id` IN (" . $regions;
					$sql .= ") OR n.`continentID` IN (" . $regions;
					$sql .= ")";
				$sql .= ")";
			}
		}
		$is_blog=false;
		if(isset($filter['is_blog']) && $filter['is_blog'] != '') {
			$sql .= " AND is_blog = 'Y' ";
			$is_blog=true;
		} else 	
			$sql .= " AND is_blog = 'N' ";
		$mapLimit = 20;
		if(isset($filter['timeLine']) || isset($filter['timeline'])) {
			$dtFrom = $GLOBALS['currDate'];
			if( isset($filter['timeLine']) )//coming in android
				$timeLine = $filter['timeLine'];
			if( isset($filter['timeline']) )//coming in ios
				$timeLine = $filter['timeline'];
			switch(strtolower($timeLine)){
				case '1w':
					$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -7 days'));
					$mapLimit = "50";
					//$sql .= " AND DATE(n.`post_date`) >= '$dtFrom'";
				break;
				case '2w':
					$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -14 days'));
					$mapLimit = "50";
				break;
				case '2d':
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 2 DAY)";
					$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -2 days'));
					$mapLimit = "30";
				break;
			}
			
			$sql .= " AND DATE(n.`post_date`) >= '$dtFrom'";
		}
		if(isset($filter['fromDate']) && $filter['fromDate'] != ''){
			$dt = date('Y-m-d', strtotime($filter['fromDate']));
			$sql .= " AND  DATE(n.`post_date`) >= '$dt'";
		}
		
		if(isset($filter['toDate']) && $filter['toDate'] != '' && $filter['toDate'] != 'tillDate'){
			$dt =  date('Y-m-d', strtotime($filter['toDate']));
			$sql .= " AND  DATE(n.`post_date`) <= '$dt'";
		}
		
		if(strtolower($source) == 'newsletter'){
			$sql .= " AND DATE(n.`post_date`) = '".date_yesterday()."'";
		}
		
		//we want to show all bookmarks done by the user in steelmint/colamint site. so we are not checiing this condition in case of fetching bookmarks
		if($source != 'bookmark' && $source != 'bookmarks' && strtolower($source) != 'newsletter'){
    		if(in_array($memid, $GLOBALS['CM_MEMID_ALLOWED'])===false){
    			if(isset($filter['debug']) && $filter['debug'] == 1) {
    			    echo "<br />entered . $appType";
    			}
    			$web_domain = $appType=='CM' ? "coalmint.com" : "steelmint.com";
    			/*$sql .= " AND MATCH(n.`for_smgroup_company`) AGAINST ('";
    		
    			if(strpos($web_domain, "coalmint.com") !== false) {
    				$sql .= "coalmint.com";
    			} else {
    				 $sql .= "steelmint.com";
    			}
    		
    		
    			$sql .= "' IN BOOLEAN MODE)";*/		
    		}
		}
		
		if(isset($filter['authorID']) && $filter['authorID']>0) {	
			$sql .= " AND n.author_id='".$filter['authorID']."'";
		}
		
		$sort_data = array(
			'n.`post_title`',
			'n.`author_name`',
			'n.`post_date`',
			'n.`created_at`',
			'n.`most_read`',
			't.`tags`',
			'n.`created_at`'
		);

		if (isset($filter['sort']) && in_array($filter['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $filter['sort'];
			if(isset($filter['order']))
				$sql .= " " . $filter['order'];
		}elseif($orderBY!=''){
			$sql .= " ORDER BY " . $orderBY;
		}else {
			$sql .= " ORDER BY n.`created_at` Desc";
		}
		
		if( date("Y-m-d") == '2020-08-22' || date("Y-m-d") == '2020-08-23' )//want to show post_id = 177912 on top on these 2 days
			$sql = str_replace("ORDER BY", "ORDER BY case when post_id = 177912 then 1 else 99 end,",   $sql);
		
		if(isset($filter['relatedItemID']))
			$limit = RELATED_LIMIT;
		elseif($source=='home')
			$limit = DEFAULT_LIMIT_HOME;		
		elseif($source=='home_website')					
			$limit = 5;
		elseif(isset($filter['featuredTab']))
			$limit = 5;
        elseif(isset($filter['API_Key']) && $filter['API_Key']=='1dP9kOjmxZDt1')
			$limit = 100;
		else
			$limit = DEFAULT_NEWS_LIMIT;
		
		if(isset($filter['association_pmai']) && $filter['association_pmai'] == 'Y')
			if(isset($filter['widget_name']) && $filter['widget_name'] == 'coalshastra')
				$limit = 4;
			else
				$limit = 5;
			
		if(strtolower($source) == 'newsletter')
			$sql .= " LIMIT 0, 600";
		elseif(strtolower($source)!='mapview'){//pagination concept not required for mapView
			if($isPagination==true)
				$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		}else{
			//if(!isset($filter) || empty($filter)){//limit set as 20 for mapview default case
				$sql .= " LIMIT 0, $mapLimit";
		//	}
		}
		
		if((isset($filter['debug']) && $filter['debug'] == 1) ){
            echo "<pre>$visitHistory==".$chkVisitHistoryCount ."------->2nd sql:", $sql, "</pre>";
          print_r($filter);
        } 		
          // echo $sql; 
        //added for app to handle blank market in listing pages 
        if(empty($filter['selected_market']) && $resourceType=='app')
            $filter['BlankMarketFlagHandler']='set';
		$query = mysql_query($sql);
		$region='';$regionCnt = 0;
		$viewMore = array();
		while($row = mysql_fetch_assoc($query)){ 
			$pageType1 = $pageType;
			$result = array();
			//$result['itemId'] = strval($row['post_id']);
			$result['itemID'] = intval($row['post_id']);
			$result['timeToRead'] = $row['f_timetoread'];
			$result['title'] = removeMSWordattributes(html_entity_decode( stripslashes($row['post_title']), ENT_QUOTES));			
			
			//comvert single quotes of MS word
			$row['post_content'] = str_replace(array("&amp;#8217;","&amp;#8216;"), "&#039;", $row['post_content']);
			$row['post_content'] = str_replace(array("#8217;","#8216;"), "&#039;", $row['post_content']);

            //comvert - of MS word
			$row['post_content'] = str_replace(array("&amp;#8211;","&amp;#8212;"), "-", $row['post_content']);
			$row['post_content'] = str_replace(array("#8211;", "#8212;"), "-", $row['post_content']);			

            //comvert doublequotes of MS word
			$row['post_content'] = str_replace(array("&amp;#8220;","&amp;#8221;"), "&#34;", $row['post_content']);
			$row['post_content'] = str_replace(array("#8220;", "#8221;"), "&#34;", $row['post_content']);			
			
			
			
			if($pageType1=='pre'){
				$content = 'hidden';
			}else{//if post
				$user = new User($memid, $appType);
				 if(($source=='portfolio' || $sourceNew=='commoditywise' || $sourceNew=='regionwise'  || $filter['BlankMarketFlagHandler']=='set') && empty($filter['selected_market'])){
                    $isAccessible =  $user->isAccessible($resourceType, $section='Insights', $itemID='', $itemDate=$row['post_date'],'',$filter['selected_market']);
                    $com_arr=array();                    
                    if(!empty($row['subsubCommodityID']))
                        $com_arr[] = $row['subsubCommodityID'];
                    elseif(!empty($row['subCommodityId']))
                        $com_arr[] = $row['subCommodityId'];
                    elseif(!empty($row['commodityId']))
                        $com_arr[] = $row['commodityId'];
                    
                    $isAccessibleMkr =  $user->isAccessibleMarketWise('',$com_arr);
                    if($isAccessibleMkr==-1 && $pageType1=='post'){
                        $pageType1='post'; 
                    }else{
                        $pageType1='pre';
                    }

                }
				else{
                    $isAccessible =  $user->isAccessible($resourceType, $section='Insights', $itemID='', $itemDate=$row['post_date'],'',$filter['selected_market']);
                    ///if($memid==116688)print_r(session()->all());
                    if($isAccessible==-1){
                        $pageType1='post'; 
                    }else{
                        $pageType1='pre';
                    }
				}
				
				$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
			
				if(isset($filter['language']) && !empty($filter['language']) && strtolower($filter['language'])!='en'){
					if($row['news_in_'.$filter['language'].'']){
						$news_in_language = html_entity_decode($row['news_in_'.$filter['language'].''], ENT_QUOTES);
						if(strpos($news_in_language, "0997788997788990") !== false){
							list($_news_description, $_news_title) = explode('0997788997788990', $news_in_language);
							$result['post_title'] = $_news_title;
							$content = $_news_description;
						}else{
							$content = (html_entity_decode($news_in_language, ENT_QUOTES));
						}
					}
				}
			}
			
			if(isset($filter['itemID']) && ($visitItemSeen==true || $visitHistory < $chkVisitHistoryCount) && ($pageType1=='pre' || Session::get($filter['selected_market'])['userService'] == 'Standard' || Session::get($filter['selected_market'])['userService'] == 'Corporate Standard' || Session::get($filter['selected_market'])['userService'] == 'Price Only' || Session::get($filter['selected_market'])['userService'] == 'Free Trial'))
			{			
				if(empty(Session::get($filter['selected_market'])['userType'])){
					$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
					$pageType1='post';
				}elseif(stripos(Session::get($filter['selected_market'])['sectionsIncludes'], "Insights") === false || Session::get($filter['selected_market'])['userService'] == 'Standard' || Session::get($filter['selected_market'])['userService'] == 'Corporate Standard' || Session::get($filter['selected_market'])['userService'] == 'Price Only' || Session::get($filter['selected_market'])['userService'] == 'Free Trial'){
				    $content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
					$pageType1='post';
				}else{
					$content = 'hidden';
				}
			}elseif($pageType1=='pre'){
				$content = 'hidden';
			}
			
			/* $isOpenNews = qryToCommaSepString("select id from tbl_open_news where news_id = " . $row['post_id']);
			if( $isOpenNews != '' ){ */
			if( strtotime($row['openNewsTillDate'])>=strtotime(date('Y-m-d H:i')) ){
				$pageType1='post';
				$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
			}
			if(isset($filter['is_blog']) && $filter['is_blog'] != '') {
				$pageType1='post'; 
				$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
			}
			
			$breaks = array("\n", "\r","\t");
			$content = str_replace($breaks, " ", $content);
			$content = preg_replace('/\\\"/im', '"', $content);
			$content = preg_replace('/\\"/im', '"', $content);				
			
			$row['href'] = str_replace("https://www.steelmint.com/insights/", config('constants.siteUrl')."insights/detail/", $row['href']);
			$href = $row['href'];
			$url_parts = parse_url($row['href']);
// 			if(isset($url_parts['path'])) {
// 				if(strpos($web_domain, "coalmint.com") !== false) {
// 					$href = "https://www.coalmint.com/". rtrim(ltrim($url_parts['path'], '/'), '/');
// 				}else{
// 					$href = BASEURL . rtrim(ltrim($url_parts['path'], '/'), '/');
// 				}
// 			}
			$result['href'] = $href;
			
			if($resourceType=='app')
				$post_date = date('d M H:i', strtotime($row['post_date'] . " " . $row['post_time'])).' IST';//by akash on 01/04/20
			else
				$post_date = date('M d, Y H:i', strtotime($row['post_date'] . " " . $row['post_time']));
			//$post_date = date('c', strtotime($row['post_date'] . " " . $row['post_time']));
			//$post_date = date('Y-m-d H:i:s', strtotime($row['post_date'] . " " . $row['post_time']));
			
			
			//uncomment following code if you don't want to show actual image to pre login users
/* 			if($resourceType=='app' && $pageType=='pre')
				$imageHidden = BASEURL. "api/public/assets/sm_default_medium.jpg";
			elseif($resourceType=='web' && $pageType=='pre')
				$imageHidden = BASEURL. "assets/img/tender-login.png"; */
			
			//if($resourceType == 'app'){
				//$content = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport"content="initial-scale=1.0, user-scalable=no" /></head><body><div style="width:90%;margin:auto;">' . $content . '</div></body></html>';
				$content = str_replace('<li>', "<li style='list-style-type:square !important;'>", $content);
				$content = str_replace('</li>', "<br/><br/></li>", $content);
			//}
			
			if(isset($filter['association_pmai']) && $filter['association_pmai'] == 'Y'){
				$content = html_cut($content, 200);
				$content = str_replace('<link href="https://www.steelmint.com/css/wp_style.css" rel="stylesheet" type="text/css"/>', "", $content);
				$content = strip_tags($content);
			}

			if(strtolower($source) == 'newsletter'){
				$content = str_replace('<link href="https://www.steelmint.com/css/wp_style.css" rel="stylesheet" type="text/css"/>', "", $content);
				$content = strip_tags($content);
			}
			 
			if($resourceType == 'app') {
			    /*$content = preg_replace("/<span.*?>(.*)?<\/span>/i","$1", $content);*/
			    $content = preg_replace('/<span[^>]+\>/i', '', $content); 
				$content = str_replace("</span>","", $content);
			}    
			
			if( $result['itemID'] >= 424534 )
			    $content = str_replace("https://aws.steelmint.com/", "https://wp-insights-sm.s3.ap-south-1.amazonaws.com/", $content);
			
			$result['description'] = $content;
			
			//$result['description'] = utf8_decode($content);	
			
			//uncomment following code if you don't want to show actual image to pre login users
//			$result['thumbnailImageURL'] = $pageType=='post'?str_replace("http://", "https://", $row['small_image']):$imageHidden;
//			$result['mainImageURL'] = $pageType=='post'?str_replace("http://", "https://", $row['image']):$imageHidden;
//https://img.steelmint.com", "https://www.steelmint.com/sm_group_events/images/events/{$row["image"]}") . "?tr=h-290,w-230";
			//if($memid==56350)
			///$row['image']="https://www.steelmint.com/earth.gif";
			$result['f_excerpt'] = $row['f_excerpt'];	
			$result['f_tags'] = $row['f_tags']?$row['f_tags']:'';		
			//Commented by YKV to avoid img.steelmint.com broken image issue - 11 Feb'23
			//$result['mainImageURL'] = str_replace("https://www.steelmint.com","https://img.steelmint.com", str_replace("http://", "https://", $row['image']));
            $row['image'] = str_replace("wp-insights-sm.s3.ap-south-1.amazonaws.com","d199amilqw5tyr.cloudfront.net", str_replace("http://", "https://", $row['image']));			
           //$result['mainImageURL'] = str_replace("wp-insights-sm.s3.ap-south-1.amazonaws.com","d199amilqw5tyr.cloudfront.net", str_replace("http://", "https://", $row['image']));			
			                               
			$result['mainImageURL'] = str_replace("http://", "https://", $row['image']);
			$basename = basename($result['mainImageURL']);			
			$filename = dirname($result['mainImageURL']);
			
			//Commented by YKV to avoid img.steelmint.com broken image issue - 11 Feb'23
			/*
			if($resourceType=='app')
				//$result['mainImageURL'] = $filename . "/tr:h-250,w-400,q-100/" . $basename;
				$result['mainImageURL'] = $filename . "/tr:cm-pad_resize,w-600,q-100/" . $basename;
			else
				$result['mainImageURL'] = $filename . "/tr:ar-2-1,w-800,c-at_max/" . $basename;
				
			*/
			// if($resourceType=='app')
				// $result['thumbnailImageURL'] = $filename . "/tr:ar-2-1,w-200,c-at_max/" . $basename;
			// else
				$result['thumbnailImageURL'] = $filename .'/'. $basename;
			
			//$result['thumbnailImageURL'] = $filename . "/tr:h-144,w-192,c-at_max/" . $basename;
			$imgType='image';
			if($basename){
				$info = pathinfo($basename);
				if(strtolower($info['extension'])=='gif')
					$imgType='gif';
			}			
			$result['videoURL'] = str_replace("http://", "https://", $row['videoURL']);
			$result['thumbnailType'] = $row['videoURL']!=''?'video':$imgType;
			$result['postedDateTime'] = $post_date;
			$result['datePublished'] = date('Y-m-d H:i:s', strtotime($row['post_date'] . " " . $row['post_time']));
			$result['isPostOpenToAll'] = strtotime($row['openNewsTillDate'])>=strtotime(date('Y-m-d H:i'))?'y':'n';
			
			$result['latitude'] = (double)$row['latitude'];
			$result['longitude'] = (double)$row['longitude'];
			$result['commodityID'] = intval($row['subCommodityId']);
			$result['commodityName'] = $row['commodityName'];
			$result['fbCommodity'] = empty($row['sub_category'])?'':$row['sub_category'];
			//$result['regionID'] = intval(end(explode(",",$row['regionIds'])));
			$result['regionID'] = intval($row['regionID']);
			$result['regionName'] = $row['regionName']!=''?$row['regionName']:'Others';
			$result['isBookmarked'] = $row['isBookmarked']!='' ? 'y':'n' ; 
			$result['showMoreOrLess'] = $row['showMoreOrLess'];
			$result['noOfReads'] = $row['most_read'] ? intval($row['most_read']) : 0; 
			$result['authorDetails'] = array(
											"authorID"=>intval($row['author_id']),
											"imageURL"=>$row['author_imageURL'],
											"name"=>$row['author_name'],
											"emailId"=>$row['author_email']==''?$row['author']:$row['author_email'],
											"socialAccounts"=>array(
												'facebook'=>$row['author_facebookId'],
												'twitter'=>$row['author_twitterId'],
												'linkedIn'=>$row['author_linkedIn'] 
											)
										);
			
			/*if(strtolower($source) == 'mapview' && $region == $row['regionName']){
				$mainEle[$postId]['viewMore'][] = $result;
			}else*/{				
				$region = $row['regionName'];
				/*if(count($viewMore)>0){
					$result['viewMore'][] = $viewMore;
					$viewMore = array();
				}*/
				$postId = $row['post_id'];
				$mainEle[$postId] = $result;				
			}
			//$news[] = $result;
		}
		
		foreach($mainEle as $ele):
			$news[]=$ele;
		endforeach;
		if(isset($filter['debug']) && $filter['debug'] == 1) {
		
		    echo '<pre>';print_R($news);
		}
		if($type=='default'){
			//json file $news;
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $news;
    }
	
	//tenders
	//DEFAULT_TENDERS_LIMIT
	public static function getTendersRows($memid=0, $source='listing', $resourceType="app", $type='default', $filter=array(), $pageType1='post', $limit=5, $offset=0, $appType='SM'){
		$result=array(); 
        $tenders = array();
		$currDate = date('Y-m-d H:i:s');
		$sql = "";				  
		$sql .= " WHERE n.`id` > 0 ";//and n.`post_id`<>107846

		if($source!='') {//source
			switch($source){				
				case 'listing':
				break;
				case 'mapView':
				break;
				case 'portfolio':
					$sqlTC = "select regionId, commodityId from tbl_user_portfolio where user_id=".$memid." and type='tender' order by id desc limit 1"; 
					$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
					$temp = mysql_fetch_array($rsTC,MYSQL_ASSOC);	
					
					if($temp['commodityId']){
						$commodityIDs = $temp['commodityId'];
						$filter['commodityID'] = explode(',',$commodityIDs);
					}
					if($temp['regionId']){
						$regionIDs = $temp['regionId'];
						$filter['regionID'] = explode(',',$regionIDs);
					}
					
					if(empty($filter['commodityID']) && empty($filter['regionID'])){
						return $result;
					}
				break;
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark':
					$common = new Common();
					$bookMarkedIds = $common->getUserBookmarksV2019($resourceType, $memid, $section='tender', $status='', $event_id=0);
					if(count($bookMarkedIds)>0)
						$filter['itemID'] = $bookMarkedIds;
					else
						$filter['itemID'] = array(0);
				break;
				case 'alerts':				
				case 'alert':
					$common = new Common();
					$alerts = $common->getUserAlertsV2019($resourceType, $memid, $type='tender');//all tenders
					if(empty($alerts))
						$alerts = array(0);
					//print_r($alerts);
					$filter['itemID'] = array_keys($alerts);
				break;
				case 'recent':
                    $orderBY = " post_date Desc, post_time Desc ";
				break;
				case 'featured':
                    $filter['isFeatured'] = 1;
					//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'similar': 
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
					$sqlTC = "select subCommodityID, sc.`country_id` as regionID
								from tbl_tenders as n
								left join tbl_state_city sc
								ON sc.ID = n.cityID
								where  n.id = '".$filter['relatedItemID']."'
							";
					$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC); 	
					$cr_data = mysql_fetch_assoc($rsTC);
					
					if(empty($cr_data)){
						$source= 'home';
					}else{
						$filter['commodityID'] = $cr_data["subCommodityID"]; 
						$filter['regionID'] = $cr_data["regionID"];
												
						$source= '';						
					}
					$chkSource = false;	
				break;
				case 'recommendedTenders':
				case 'recommendedtenders':
					$common = new Common();
					$cr_data = $common->getUserPortfolioV2019($memid, 'tender', $appType);
					if(empty($cr_data)){
						$source= 'home';
					}else{
						$filter['commodityID'] = array(); 
						$filter['regionID'] = array();
						
						foreach($cr_data as $K=>$v){
								array_push($filter['commodityID'],$v["commodityId"]);
								array_push($filter['regionID'],$v["regionId"]);
						}
						$source= '';						
					}
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				default: //like listing , mapview and others
					//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
					$orderBY = " post_date Desc, post_time Desc ";
				break;
			}			
		}
		
		if(isset($filter['searchTerms']) && !empty($filter['searchTerms'])) {
			
			$cd = date("Y-m-d");
			$ct = date("H:i:s");
			mysql_query("
				insert into tbl_searches 
				values (
				'',
				'$cd',
				'$ct',
				$memid,
				'tenders',
				'" . htmlspecialchars($filter['searchTerms'], ENT_QUOTES) . "',
				'$resourceType'
				)"
			);
			
			$sql .= " AND (";

			$implode = array();

			$words = explode(' ', trim(preg_replace('/\s+/', ' ', $filter['searchTerms'])));
            $words = str_replace(array("tender","tender"), "", $words);
			foreach ($words as $word) {
				$implode[] = ' (city_name REGEXP "[[:<:]]' . $word . '[[:>:]]" OR state_name REGEXP "[[:<:]]' . $word . '[[:>:]]" OR country REGEXP "[[:<:]]' . $word . '[[:>:]]" OR title REGEXP "[[:<:]]' . $word . '[[:>:]]" OR sub_category_all  REGEXP "[[:<:]]' . $word . '[[:>:]]" OR  category_all REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  company_name REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  buy_sell REGEXP "[[:<:]]' . $word . '[[:>:]] " OR offer_type REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  c.country REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  sc.state_name REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  region REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  description REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  remarks REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  floor_price REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  qty REGEXP "[[:<:]]' . $word . '[[:>:]] " OR  grade REGEXP "[[:<:]]' . $word . '[[:>:]]  " OR  contact_person REGEXP "[[:<:]]' . $word . '[[:>:]]  " OR  email REGEXP "[[:<:]]' . $word . '[[:>:]]   " OR  mobile REGEXP "[[:<:]]' . $word . '[[:>:]]  " OR  product REGEXP "[[:<:]]' . $word . '[[:>:]]")   ';
			}

			if ($implode) {
				$sql .= " " . implode(" AND ", $implode) . "";
			}

			$sql .= ")";
		}   		
		
		if($filter['sliderID']!=''){
			$common = new Common();			
			$sliderRes = $common->getSliderDetails($filter['sliderID']);
			
			if(empty($sliderRes)){								
				$filter['commodityID'] = array(); 
				$filter['regionID'] = array();
			}else{
				if($sliderRes['commodityID'])
					$filter['commodityID'] = array($sliderRes['commodityID']); 
				if($sliderRes['regionID'])
					$filter['regionID'] = array($sliderRes['regionID']); 
			}
		}
		
		//for 'recommendedTenders'
		if(isset($cr_data) && $source==''){
				$sql .= " AND (";
				if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
					
						$sql .= " n.`subCommodityID` IN (";
						$sql .= implode(", ", $filter['commodityID']);
						$sql .= ")";				
				}
				
				if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
					$regions = implode(",", $filter['regionID']); 	
					$sql .= " OR ";	
						$sql .= " sc.`country_id` IN (" . $regions;
						$sql .= ")";
				}
				
				$sql .= ")";
		} else {
			if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
				$sql .= " AND (";
					$sql .= " commodityID IN (";
					$sql .= implode(",", $filter['commodityID']);
					$sql .= ") OR ";
					$sql .= " subCommodityID IN (";
					$sql .= implode(",", $filter['commodityID']);
					
					$sql .= ") OR ";
					$sql .= " subsubCommodityID IN (";
					$sql .= implode(",", $filter['commodityID']);
					$sql .= ")";
				$sql .= ")";
			}
			if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
				$flag = 0;	
				if(strtolower($source) == "mapview" || strtolower($source) == "regionwise" || strtolower($source) == "regioncommoditywise"){
					$continents = implode("," , $filter['regionID']);
					$regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID in ($continents) OR id  in ($continents)) ");
					$flag = 1;
				} else {
					$regions = implode(",", $filter['regionID']);
					$flag = 1;
				}
				if( $flag == 1 ){
					$sql .= " AND sc.`country_id` IN (" . $regions;
					$sql .= ")";		    
				}
			}			
		}
			
		if(isset($filter['tenderType']) && strtolower($filter['tenderType'])!='all'){
			$sql .= " AND n.`buy_sell` = '" . $filter['tenderType'] ."'";
		}		
		
		if(isset($filter['company']) && !empty($filter['company'])) {		
			$sql .= " AND `company_name` IN ('";
			$sql .= implode("', '", $filter['company']);
			$sql .= "')";	
		}elseif(isset($filter['companyName']) && !empty($filter['companyName'])) {
			$sql .= " AND `company_name` IN ('";
			$sql .= implode("', '", $filter['companyName']);
			$sql .= "')";	
		}
		
		if(isset($filter['quantity']) && $filter['quantity']>0) {			
			/* $sql .= " AND `qty` IN ('";
			$sql .= implode("', '", $filter['quantity']);
			$sql .= "')";	 */
		}
		
		if(isset($filter['offerType']) && !empty($filter['offerType'])) {			
			$sql .= " AND `offer_type` IN ('";
			$sql .= implode("', '", $filter['offerType']);
			$sql .= "')";	
		}
		//"status" : "expired/live",
		if(isset($filter['status'])){
			if(isset($filter['status']) && strtolower($filter['status'])=='expired') {
				$sql .= " AND n.due_date < '".$GLOBALS['currDate']."' ";
			}else{
				$sql .= " AND n.due_date <> '0000-00-00 00:00:00' AND STR_TO_DATE(n.due_date, '%Y-%m-%d') >= '".$GLOBALS['currDate']."'";
			}	
		}else{
			$sql .= " AND n.due_date <> '0000-00-00 00:00:00' AND STR_TO_DATE(n.due_date, '%Y-%m-%d') >= '".$GLOBALS['currDate']."'";
		}
		
		if(isset($filter['Date']) || isset($filter['date'])) {			
			$dd = isset($filter['Date'])?explode("_", $filter['Date']):explode("_", $filter['date']);
			$_days = end($dd);
			if($_days>0){
				$max_date =  date('Y-m-d' , strtotime($_date.' +'.$_days.' days'));
				$sql .= " AND STR_TO_DATE(n.due_date, '%Y-%m-%d') >= '".$GLOBALS['currDate']."' AND STR_TO_DATE(n.due_date, '%Y-%m-%d') <= '".$max_date."'";	
			}
		}
		
		if(isset($filter['itemID'])) {
			if(is_array($filter['itemID']))
				$sql .= " AND n.`ID` IN (" . implode(", ", $filter['itemID']) .")";
			elseif($filter['itemID']>0)
				$sql .= " AND n.`ID` = " . (int)$filter['itemID'];
		}
		
		if(isset($filter['relatedItemID']) && !empty($filter['relatedItemID'])) {
			$sql .= " AND n.`ID` <> " . (int)$filter['relatedItemID'];
		}
		
		if(isset($filter['isFeatured'])) {			
			$sql .= " AND `isFeatured`=".$filter['isFeatured']." ";	
		}
		
		if( $appType == 'CM' ){
			$sql .= " AND `commodityID`= 401 ";	
		}
		
		//code added for App - market wise listing 
		if(!empty($filter['selected_market']) && strtolower($resourceType)=='app'){
            //and parentID=0
            $qry =  "select 
            GROUP_CONCAT(id) as commodities
            from tbl_region_commodity_master where FIND_IN_SET('".$filter['selected_market']."',f_market)  and itemtype='commodity' ";        
            $res = mysql_query($qry);
            $row = mysql_fetch_assoc($res);
            $market_commodities = $row['commodities'];
            $sql .= " AND (";
				$sql .= " commodityID IN (";
				$sql .=     $market_commodities;
				$sql .= ") OR ";
				$sql .= " subCommodityID IN (";
				$sql .=  $market_commodities;				
				$sql .= ") OR ";
				$sql .= " subsubCommodityID IN (";
				$sql .=   $market_commodities;
				$sql .= ")";
			$sql .= ")";
		}
		
		if(isset($filter['openingDate']) && strtolower($filter['openingDate'])!='' && isset($filter['closingDate']) && strtolower($filter['closingDate'])!='' ){
			$openingDate=trim($filter['openingDate']);   
			$closingDate=trim($filter['closingDate']);  
			$sql.=" AND n.opening_date >= '$openingDate 00:01' AND n.closing_date <= '$closingDate 23:59'";
		}elseif(isset($filter['openingDate']) && strtolower($filter['openingDate'])!='' )
        {
            $openingDate=trim($filter['openingDate']);            
            $sql.=" AND n.opening_date like '$openingDate%'";
        }elseif(isset($filter['closingDate']) && strtolower($filter['closingDate'])!='' )
        {
            $closingDate=trim($filter['closingDate']);           
            $sql.=" AND n.closing_date like '$closingDate%'";
        }
		
		//Condition for collections in tenders
		if(isset($filter['tagID']) && strtolower($filter['tagID'])!='' )
        {
            $sqlTC = "select query, add_condition from tbl_tender_collection where id=".$filter['tagID']; 
			$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
			$rowTC = mysql_fetch_array($rsTC,MYSQL_ASSOC);
		
			if($rowTC['query']){
				$ids = qryToCommaSepString($rowTC['query']);
				if(!$ids)
					$ids=0;
				$sql .= " AND n.`id` IN ($ids)";	
			}elseif($rowTC['add_condition']){
				$sql.=" AND (";
				$sql.=$rowTC['add_condition'];
				$sql .= ")";
			}else{
				$sql .= " AND n.`id` IN (0)";	
			}
        }
		
		if(isset($filter['innerFilterCond']) && $filter['innerFilterCond']!=''){
			$sql .= " AND (". $filter['innerFilterCond'].") ";
		}
		
		$orderBY = "";	
		
		$sort_data = array(
			'n.`opening_date`',
			'n.`due_date`',
			'n.`company_name`',
			'n.`created_at`',
			'n.`f_date`',
			't.`buy_sell`',
			'c.`country`',
			'n.`qty`'
		);
		
		if (isset($filter['sortBy'])) {
			switch($filter['sortBy']){
				case "due_date":
					$sql .= " ORDER BY n.`due_date` ASC ";
				break;
				case "publish_date_Asc":
					$sql .= " ORDER BY n.`publish_date` ASC ";
				break;
				case "publish_date_Desc":
					$sql .= " ORDER BY n.`publish_date` DESC ";
				break;
				default:
					$sql .= " ORDER BY n.`due_date` ASC";
				break;
			}			
		}elseif (isset($filter['sort']) && in_array($filter['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $filter['sort'];
			if(isset($filter['order']))
				$sql .= " " . $filter['order'];
		}elseif(isset($filter['Date']) || isset($filter['date'])) {			
			$sql .= " ORDER BY n.`due_date` ASC";
		}elseif($orderBY!=''){
			$sql .= " ORDER BY n.id=20618 desc " . $orderBY;
		}else {
			$sql .= " ORDER BY n.id=20618 desc,n.`publish_date` DESC";
		}
		
		if(isset($filter['relatedItemID']))
			$limit = RELATED_LIMIT;
		elseif(isset($cr_data))
		    $limit = RECOMMENDED_LIMIT;
		elseif($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		if($source=='portfolio'){
			$limit = 7;
			
            $a = mysql_num_rows(mysql_query("SELECT * FROM `tbl_tenders` as n 
            left outer join tbl_state_city sc ON sc.ID = n.cityID" . $sql));
            $cntBookmarkedTendersPages = ceil($a / 7);
			
		}else
			$limit = DEFAULT_LIMIT;

		if(strtolower($source)!='mapview'){//pagination concept not required for mapView
			$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		}
		
		///, (select id from tbl_user_portfolio as b where user_id=$memid and type='tenders' and appType='$appType' limit 1) as isAddedToPortfolio
		 $additional_col =",(select id from tbl_bookmarks as b where n.id=b.item_id and memid=$memid and section='tender'  and status='active'   limit 1) as isBookmarked";
		 $additional_col .=",(select id from tbl_alerts as c where n.id=c.item_id and memid=$memid and section='tender' and status='active'  order by id desc limit 1) as isSetAlert, 
				(select x_days_before from tbl_alerts as c where n.id=c.item_id and memid=$memid and section='tender' and status='active'  order by id desc limit 1) as xDaysBeforeExpiry";
		 $additional_col .=",(select action from tbl_show_more_less_like as c where n.id=c.item_id and memid=$memid and section='tender' limit 1) as showMoreOrLess";
		$sql = "select n.ID, n.f_date, n.company_name,
			  n.f_authorised ,
			  n.qty,
			  n.qty_unit,
			  n.grade,
			  DATE_FORMAT(n.opening_date,'%d %b %y') as opening_date,
			  n.opening_date as od,
			  n.closing_date,
			  DATE_FORMAT(n.due_date,'%d %b %y') as due_date,
			  n.due_date as dd,
			  n.pdf_path,
			  replace(n.sub_category, '_', ' ') sub_category,
			  replace(n.sub_category_all, '_', ' ') sub_category_all,
			  category as category_all,
			  category_all as categoryToMatch,
			  n.title,
			  n.memid,
			  n.description ,
			  n.buy_sell,
			  n.imgpath,
			  n.offer_type,
			  sc.city_name,
			  sc.state_name,
			  c.country,
			  CASE
				WHEN n.multi_loction = 1 THEN 'Multi Location'
				WHEN sc.country_id = 113 THEN concat(sc.city_name,'/',sc.state_name,'/','INDIA')
				ELSE concat(sc.city_name, '/', c.country)
			  END as region,
			  CASE
			  WHEN (n.due_date <> '0000-00-00 00:00:00' AND n.due_date >= '$currDate') THEN 'Live'
			  ELSE 'Expired'
			  END as live_expired,
			  CASE 
				WHEN n.corrigendum <> '' THEN n.corrigendum
				ELSE ''
			  END as corrigendum,
			  CASE 
				WHEN n.contact_person <> '' THEN n.contact_person
				ELSE ''
			  END as contact_person,
			  CASE 
				WHEN n.email <> '' THEN n.email
				ELSE ''
			  END as email,
			  (select name from tbl_designation where id = n.designation) 
			  as designation,
			  DATE_FORMAT(n.publish_date,'%d %b %y') as publish_date
			  ,CASE
				WHEN n.mobile<>'' then concat(n.std_code, n.mobile) 
				ELSE ''
			  END as phone_no,
			  
			  n.commodityID,
			  n.subCommodityID,
			  n.subSubCommodityID,
			  
              (SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = n.commodityID) as commodityName,
		      (SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = n.subCommodityID) as subCommodityName,
		      (SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = n.subSubCommodityID) as subSubCommodityName, 			  
			  (select itemName from tbl_region_commodity_master as cm where sc.country_id=cm.id and itemType='region') as regionName,
			  
			  sc.country_id as regionID,
			  sc.latitude,
			  sc.longitude
			  $additional_col 
			  ,address
			  from tbl_tenders as n
			  left outer join tbl_state_city sc ON sc.ID = n.cityID
			  left outer join tbl_country c ON sc.country_id = c.id
			  $sql
			  ";
         
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($filter), $sql, "</pre>";          
            $finres = array();
            $finres["dataValue"] = $sql;
            $finres["cntValue"] = implode(",", $filter);
            
           // return $finres;
        }    
		
		$user = new User($memid, $appType);
		
// 		if(isset($filter['tagID']) && strtolower($filter['tagID'])!='' ){
// 		    $query = mysql_query($sql) or die(mysql_error().$sql);
// 		}
   		 $isAccessible =  $user->isAccessible($resourceType, $section='Tenders', '', '', '', $filter['selected_market']);
            if(!empty(Session::get($filter['selected_market'])['sectionFromDate'])){
                $sectionFromDate = Session::get($filter['selected_market'])['sectionFromDate'];
                $sectionTodate = Session::get($filter['selected_market'])['sectionTodate'];			
            }
         if($filter['debug']==1)
        {
            echo "<pre>";
            print_r(session()->all());
            echo "</pre>";
        }
        
         //added for app to handle blank market in listing pages 
        if(empty($filter['selected_market']) && $resourceType=='app')
            $filter['BlankMarketFlagHandler']='set';
            
		$query = mysql_query($sql) or die(mysql_error().$sql);
		$region='';$regionCnt = 0;
		$viewMore = array();
		while($row = mysql_fetch_assoc($query)){            
            if(($source=='portfolio' ||  strtolower($source) == "regionwise" || strtolower($source) =='commoditywise' || $filter['BlankMarketFlagHandler']=='set') && empty($filter['selected_market'])){
                $com_arr=array();                
                if(!empty($row['subSubCommodityID']))
                    $com_arr[] = $row['subSubCommodityID'];
                elseif(!empty($row['subCommodityID']))
                    $com_arr[] = $row['subCommodityID'];
                elseif(!empty($row['commodityID']))
                    $com_arr[] = $row['commodityID'];
                    
                $isAccessibleMkr =  $user->isAccessibleMarketWise('',$com_arr);
                if($isAccessibleMkr==-1 && $pageType1=='post'){
                   $pageType='post'; 
                }else{
                    $pageType='pre';
                }
                 if($filter['debug']==1){
                    echo "===>";
                    print_r($isAccessibleMkr);
                    print_r($com_arr);
                }

            }else{
                $com_arr=array();
                if(!empty($row['subSubCommodityID']))
                    $com_arr = array("subSubCommodityID"=>(int)$row['subSubCommodityID']);
                elseif(!empty($row['subCommodityID']))
                    $com_arr = array("subCommodityID"=>(int)$row['subCommodityID']);
                elseif(!empty($row['commodityID']))
                    $com_arr = array("commodityID"=>(int)$row['commodityID']);
                
                $isAccessible =  $user->isAccessible($resourceType, $section='Tenders', '', '', '', $filter['selected_market'],$com_arr);          
            
                if($isAccessible==-1 && $pageType1=='post'){
                    if (strtotime($row['publish_date']) >=strtotime($sectionFromDate) && strtotime($row['publish_date']) <= strtotime($sectionTodate)){
                        $pageType='post'; 
                    }else{
                        $pageType='pre';
                    }
                }else{
                    $pageType='pre';
                }
			}
			
			
			
			//$dateDiff = $this->dateDiffInDays($row['dd'], $GLOBALS['currDate']);
			$str = strtotime($row['dd']) - (strtotime($GLOBALS['currDate']));
			$dateDiff = floor($str/3600/24);	
			
			$result = array();
			$tenderId = intval($row['ID']);
			$result['itemID'] = $tenderId;
			$result['title'] = removeMSWordattributes(html_entity_decode($row['title'], ENT_QUOTES));	
			//$row['description'] = removeMSWordattributes(html_entity_decode($row['description'], ENT_QUOTES));	
			$result['description'] = $row['company_name']." :".$row['description'] ;
			$result['type'] = 'image';///needd to change
			
			if($resourceType=='app' && $pageType=='pre'){
				//$imageHidden = $appType=='CM'?BASEURL. "api/public/assets/cm_default_medium.jpg":BASEURL. "api/public/assets/sm_default_medium.jpg";
				$imageHidden = BASEURL. "assets/img/tender-login.jpg";
			}
			elseif($resourceType=='web' && $pageType=='pre')
				$imageHidden = BASEURL. "assets/img/tender-login.jpg";
				
				
			$result['thumbnailImage'] = $pageType=='post'?env('TENDER_IMAGE_PREFIX').str_replace(' ', '%20',$row['imgpath']):$imageHidden;
			$result['imageURL'] = $pageType=='post'?env('TENDER_IMAGE_PREFIX').str_replace(' ', '%20',$row['imgpath']):$imageHidden;
			$result['thumbnailVideoImage'] = "" ;
			$result['videoUrl'] ="";
			$result['commodityID'] = (int)$row['commodityID'];
			$result['subCommodityID'] = (int)$row['subCommodityID'];
			$result['subsubCommodityID'] = (int)$row['subSubCommodityID'];
			
			$result['commodityName'] = $row['commodityName'];
			$result['subCommodityName'] = $row['subCommodityName'];
			$result['subsubCommodityName'] = $row['subsubCommodityName'];
			
			$result['regionID'] = (int)$row['regionID'];
			$result['regionName'] = is_null($row['regionName'])?'Others':$row['regionName'];
			
			$result['latitude'] = (double)$row['latitude'];
			$result['longitude'] = (double)$row['longitude'];
			$result['daysToGo'] = ($dateDiff >= 0) ? $dateDiff.' days to go':'';
			$result['daysToGoVal'] = ($dateDiff >= 0) ? $dateDiff : '';
			$result['daysToGoVal'] = strval($result['daysToGoVal']);
			$result['dueDate'] = date('d M Y',strtotime($row['dd']));
			$result['datePublished'] = date('d M Y',strtotime($row['publish_date']));
			$result['location'] = ucwords(strtolower(str_replace('/', ', ',$row['region'])));
			$row['pdf_path'] = str_replace(' ', '%20',$row['pdf_path']);
            $result['document'] = $pageType=='pre'?'hidden':"https://d3bz26k9g3a6xf.cloudfront.net/tenders/docs/" . $row['pdf_path'];
			$result['quantity'] = number_format($row['qty']);
			$result['unit'] = $row['qty_unit'];
			$result['grade'] = $row['grade'];
			$result['size'] = "";
			$result['company'] = $pageType=='pre'?'hidden':$row['company_name'];
			$result['type'] = $row['buy_sell'];
			$result['isBookmarked'] = $row['isBookmarked']!='' ? 'y':'n' ; 
			$result['isSetAlert'] = $row['isSetAlert']!='' ? 'y':'n' ; 
			if( $pageType=='post') 
				$result['xDaysBeforeExpiry'] = intval($row['xDaysBeforeExpiry'])>0 ? $row['xDaysBeforeExpiry']:'0' ; 
			else
			    $result['xDaysBeforeExpiry'] = '0';
			    
			$result['xDaysBeforeExpiry'] = strval($result['xDaysBeforeExpiry']);    
			$result['showMoreOrLess'] = $row['showMoreOrLess']; 
			if($memid>0 && $result['commodityID']>0){
				$isAddedToPortfolio = qryToCommaSepString("select id from tbl_user_portfolio as b where user_id=$memid and type='tenders'  and (commodityID like '".$result['commodityID'].",%' or commodityID like '%,".$result['commodityID']."' or commodityID like '".$result['commodityID']."') limit 1");
				$isAddedToPortfolio = 'y';
			}else
				$isAddedToPortfolio = 'n';
			
			$result['isAddedToPortfolio'] = $isAddedToPortfolio;
			$result['contactID'] = array(
												"name" => $pageType=='pre'?'hidden':$row['contact_person'],
												"phone" => $pageType=='pre'?'hidden':$row['phone_no'],
												"address" => $pageType=='pre'?'hidden':$row['address'],
												//"Location" => $row['region'],
												"email" => $pageType=='pre'?'hidden':$row['email'],
												"designation" => $row['designation'],
												"company" => $pageType=='pre'?'hidden':$row['company_name']
											);
			
			//uncomment below line when we start uploading multiple images for tenders
			//$result['gallery'] = getImagesByTableType($tenderId, $table_type='tenders');
			
			$result['gallery'][] = array( 
									"type" 			=> 	"image", 
									"imageURL"		=>	$pageType=='post'?env('TENDER_IMAGE_PREFIX').str_replace(' ', '%20',$row['imgpath']):$imageHidden, 
									"thumbnailImage"=>	$pageType=='post'?env('TENDER_IMAGE_PREFIX').str_replace(' ', '%20',$row['imgpath']):$imageHidden,
									"videoUrl"		=>	""
								);
			$tenders[]=$result;
		}

        if($source == 'portfolio') {
            $finres = array();
            $finres["dataValue"] = $tenders;
            $finres["cntValue"] = $cntBookmarkedTendersPages;
            
            return $finres;
        } else {
            return $tenders;
        }

	//	return $tenders;
	}
	
    public static function getTopTrends($memid='',$trending=''){
        $result = array();$sorted=array();
        $filter_intel["trendingTags"] = $trending;
        $filter_intel["orderBy"] = 'datePublished';
        
        if( $memid != '' )
            $result_intel = self::getIntelRowSet($memid,"app",'',$filter_intel,'post',20,0,'SM');
        else
            $result_intel = self::getIntelRowSet(0,"app",'',$filter_intel,'pre',20,0,'SM');
            
        $filter_insight["trendingTags"] = $trending;
        $filter_insight["sort"] = 'n.`created_at`';
    
        if( $memid != '' )
            $result_insight = self::getInsightsRows($memid,'listing','app','default',$filter_insight,'post',20,0,'SM');
        else
            $result_insight = self::getInsightsRows(0,'listing','app','default',$filter_insight,'pre',20,0,'SM');

        foreach($result_intel["Intels"] as $k=>$v){
		 $time = strtotime($v['datePublished']);
		  $v['thumbnailType'] = $v['type'];
		  $v['mainImageURL'] = $v['imageUrl'];
		  $v['videoURL'] = $v['videoUrl'];
		  $v['intelOrInsight'] = "Intel";

		  unset($v['type']);unset($v['imageUrl']);unset($v['videoUrl']);
          $sorted[$time]= $v; 
          
        }
		
//echo "<pre>";
//print_r($result_insight);		
		
        foreach($result_insight as $k=>$v){
            $time = strtotime($v['datePublished']);
            $v['intelOrInsight'] = "Insight";
            $sorted[$time] = $v;   
        }
         
        krsort($sorted,SORT_NUMERIC);
        $count=0;
        foreach($sorted as $k=>$v){
            if($count >= 10)
            break;
            $result[] = $v;
            $count++;
        } 

        return $result;
    }

	public static function getTendersCollectionRows($appType='SM'){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		
		if( $appType == 'SM' )
		    $colToPick = "tenderCount";
		else
		    $colToPick = "tenderCount_CM";
		
		$sqlTC = "select id as tagID, title, imageUrl, $colToPick from tbl_tender_collection where status=1"; 
		$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC); 
		$result = array();
		while($row = mysql_fetch_assoc($rsTC)){
			$row['tagID'] = intval($row['tagID']);
			$row['imageUrl'] = $row['imageUrl']!=''?BASEURL. "images/tender_collection/".$row['imageUrl']:'';
			$row['tenderCount'] = intval($row[$colToPick]);
			$result[]=$row;
		}
		
		if($type=='default'){
			//json file $result;
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $result;
	}
    //added to get market wise data - for app (24-july-24)
    public static function getTendersCollectionRowsBM($appType='SM',$filters=array()){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$colToPick = "tenderCount";
		/*if( $appType == 'SM' )
		    $colToPick = "tenderCount";
		else
		    $colToPick = "tenderCount_CM";
		*/
		 if(!empty($filters['selected_market'])){
           $where = " and  f_market='".$filters['selected_market']."' "; 
		 }
		$sqlTC = "select id as tagID, title, imageUrl, $colToPick from tbl_tender_collection_bm where status=1 $where "; 
		$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC); 
		$result = array();
		while($row = mysql_fetch_assoc($rsTC)){
			$row['tagID'] = intval($row['tagID']);
			$row['imageUrl'] = $row['imageUrl']!=''?BASEURL. "images/tender_collection/".$row['imageUrl']:'';
			$row['tenderCount'] = intval($row[$colToPick]);
			$result[]=$row;
		}
		
		if($type=='default'){
			//json file $result;
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $result;
	}
	
	public static function updte(){
	    $sqlTC = "select id as tagID from tbl_tender_collection where status=1";
	    $rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);$filter=array(); 
	    while($row = mysql_fetch_assoc($rsTC)){
	     $filter["tagID"] = intval($row['tagID']);
	     $filter["update_count"] = "Y";
	     self::getTendersRows($memid=0, $source='listing', $resourceType="app", $type='default', $filter, $pageType='post', $limit=5, $offset=0, $appType='SM');
	    }
	}
	
	public static function getTrendingRows($type='', $appType='SM'){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$sqlTC = "select id as tagID, f_title as title, f_image as imageUrl from tbl_trending_tags where status=1"; 
		$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC); 
		$result = array();
		while($row = mysql_fetch_assoc($rsTC)){
			$row['tagID'] = intval($row['tagID']);
			$row['imageUrl'] = $row['imageUrl']!=''?BASEURL. "images/trending_tags/".$row['imageUrl']:'';
			$sql = "select sum(count) from (select count(distinct `itemId`) as count from `intel` where FIND_IN_SET({$row['tagID']},`trending_tag`) > 0  union all select count(distinct `post_id`) from `tbl_news_post` where FIND_IN_SET({$row['tagID']},`trending_tag`) > 0) AS k";
			$counts = mysql_query($sql);
			$count = mysql_fetch_row($counts);
			$row['tagCount'] = intval($count[0]);
			$result[]=$row;
		}
		
		if($type=='default'){
			//json file $result;
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $result;
	}

	public static function getTendersCount($resourceType="app", $filters = array()){
		//include_once "/home/steelmin/public_html/inc/config1.php";
        $icond = array("Iron Ore"=>"iconIronore","Steel"=>"iconSteel","Coal"=>"iconCoal","Met Coke"=>"iconCoal","Pet Coke"=>"iconCoal","Non Coking Coal"=>"iconCoal","Coking Coal"=>"iconCoal","Scrap & Metallics"=>"iconMetallic","Ferro Alloy"=>"iconFerro");
		$cd = date("Y-m-d");
		$csql = '';
		if(isset($filters['commodityID']) && !empty($filters['commodityID'])) {
			
				$csql .= " and t.`commodityID` IN (";
				$csql .= implode(", ", $filters['commodityID']);
				$csql .= ")";				
		}
		
		if($resourceType == "app"){
            //code added for App - market wise listing 
            if(!empty($filters['selected_market'])){
            //and parentID=0
                $qry =  "select 
                GROUP_CONCAT(id) as commodities
                from tbl_region_commodity_master where FIND_IN_SET('".$filters['selected_market']."',f_market)  and itemtype='commodity' ";        
                $res = mysql_query($qry);
                $row = mysql_fetch_assoc($res);
                $market_commodities = $row['commodities'];
                $market_sql = " AND (";
                    $market_sql .= " commodityID IN (";
                    $market_sql .=     $market_commodities;
                    $market_sql .= ") OR ";
                    $market_sql .= " subCommodityID IN (";
                    $market_sql .=  $market_commodities;				
                    $market_sql .= ") OR ";
                    $market_sql .= " subsubCommodityID IN (";
                    $market_sql .=   $market_commodities;
                    $market_sql .= ")";
                $market_sql .= ")";
            }
			$sql = "select res1.*
			from
			(
				SELECT     buy_sell, commodityID, count(id) as `cnt`
				FROM     tbl_tenders
				WHERE  due_date <> '0000-00-00 00:00:00'
				AND    due_date >= '$cd'
				$market_sql
				group by buy_sell, commodityID    
				
				union    
				
				SELECT buy_sell, subCommodityID, count(id) as `cnt`
				FROM tbl_tenders
				WHERE   due_date <> '0000-00-00 00:00:00'
				AND     due_date >= '$cd'
				$market_sql
				$csql
				group by buy_sell, subCommodityID
			) as res1
			order by res1.buy_sell, res1.commodityID, res1.cnt";
			$rs = mysql_query($sql) or die(mysql_error().$sql);$cid='';$type='';
			//echo "dgdd";
			$temp = array();
			while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
				if($row["buy_sell"] == "Sell"){
					$type="sell";
				 } else if($row["buy_sell"] == "Buy"){
					$type="buy";
				 } else if($row["buy_sell"] == "Services"){
					$type="service";
				 }
				$result[$type][] = array("id"=>intval($row['commodityID']),"count"=>intval($row['cnt']));
				
				if(array_key_exists(intval($row['commodityID']), $temp) === 0)
					$temp[intval($row['commodityID'])] = intval($row['cnt']);
				 else 
					$temp[intval($row['commodityID'])] += intval($row['cnt']);
			}
			
			
			foreach($temp as $k=>$v){
				$result["All"][] = array("id"=>$k,"count"=>$v);
            }
		} elseif( isset($filters['app_type']) && $filters['app_type'] == 'CM') {
			$sql = "select res1.*
			from
			(
				SELECT     buy_sell, subCommodityID as commodityID, count(t.id) as `cnt`, tm.itemName as commodityName, f_order_by
				FROM     tbl_tenders t LEFT JOIN tbl_region_commodity_master tm 
				ON t.subCommodityID = tm.ID
				WHERE  due_date <> '0000-00-00 00:00:00'
				AND    due_date >= '$cd' AND tm.itemType='commodity'
				$csql
				group by buy_sell, subCommodityID	
			) as res1
			order by res1.buy_sell, res1.f_order_by, res1.cnt";
			///order by res1.buy_sell, res1.commodityID, res1.cnt";
			$rs = mysql_query($sql) or die(mysql_error().$sql);$cid='';$type='';
			//echo "dgdd";
			$temp = array();
			while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
				if($row["buy_sell"] == "Sell"){
					$type="sell";
				 } else if($row["buy_sell"] == "Buy"){
					$type="buy";
				 } else if($row["buy_sell"] == "Services"){
					$type="service";
				 }
				$result[$type][] = array("id"=>intval($row['commodityID']),"count"=>intval($row['cnt']),"iconClass"=>$icond[$row['commodityName']] ,"commodityName"=>$row['commodityName']);
				
				$cname[$row['commodityID']] = array("iconClass"=>$icond[$row['commodityName']] ,"commodityName"=>$row['commodityName']);

				if(array_key_exists(intval($row['commodityID']), $temp) === 0)
					$temp[intval($row['commodityID'])] = intval($row['cnt']);
				 else 
					$temp[intval($row['commodityID'])] += intval($row['cnt']);
			}
			
			
			foreach($temp as $k=>$v){
				$result["All"][] = array("id"=>$k,"count"=>$v, "iconClass"=>$cname[$k]["iconClass"],  "commodityName"=>$cname[$k]["commodityName"]);
			}
		} else {
			$sql = "select res1.*
			from
			(
				SELECT     buy_sell, commodityID, count(t.id) as `cnt`, tm.itemName as commodityName, f_order_by
				FROM     tbl_tenders t LEFT JOIN tbl_region_commodity_master tm 
				ON t.commodityID = tm.ID
				WHERE  due_date <> '0000-00-00 00:00:00'
				AND    due_date >= '$cd' AND tm.itemType='commodity'
				$csql
				group by buy_sell, commodityID	
			) as res1
			order by res1.buy_sell, res1.f_order_by, res1.cnt";
			///order by res1.buy_sell, res1.commodityID, res1.cnt";
			$rs = mysql_query($sql) or die(mysql_error().$sql);$cid='';$type='';
			//echo "dgdd";
			$temp = array();
			while($row = mysql_fetch_array($rs,MYSQL_ASSOC)){
				if($row["buy_sell"] == "Sell"){
					$type="sell";
				 } else if($row["buy_sell"] == "Buy"){
					$type="buy";
				 } else if($row["buy_sell"] == "Services"){
					$type="service";
				 }
				$result[$type][] = array("id"=>intval($row['commodityID']),"count"=>intval($row['cnt']),"iconClass"=>$icond[$row['commodityName']] ,"commodityName"=>$row['commodityName']);
				
				$cname[$row['commodityID']] = array("iconClass"=>$icond[$row['commodityName']] ,"commodityName"=>$row['commodityName']);

				if(array_key_exists(intval($row['commodityID']), $temp) === 0)
					$temp[intval($row['commodityID'])] = intval($row['cnt']);
				 else 
					$temp[intval($row['commodityID'])] += intval($row['cnt']);
			}
			
			
			foreach($temp as $k=>$v){
				$result["All"][] = array("id"=>$k,"count"=>$v, "iconClass"=>$cname[$k]["iconClass"],  "commodityName"=>$cname[$k]["commodityName"]);
			}
		}
	    //include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $result;
    }
	///public static function getPricesFilterNew($section='prices', $appType='SM'){
	public static function getPricesFilterNew($memid=0, $appType='SM', $deviceType=''){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$result = array();//and commodityID=408
		if( $appType == 'CM' )
			$where_condition=" WHERE category<>'INDEX' and subCommodityID>0 and commodityID = 401 ";//AND parentID> 0 and not 'Logistics' ; only  coal
		else
			$where_condition=" WHERE category<>'INDEX' and subCommodityID>0 AND commodityID<>475";//AND parentID> 0 and not 'Logistics'
		
		
		$_sql = "SELECT id, 
			(select itemName from tbl_region_commodity_master as cm where m.commodityID=cm.id and itemType='commodity') as category, 
			(select itemName from tbl_region_commodity_master as cm where m.subCommodityID=cm.id and itemType='commodity') as sub_category, 
			(select itemName from tbl_region_commodity_master as cm where m.subSubCommodityID=cm.id and itemType='commodity') as sub_sub_category, commodityID, subCommodityID, subSubCommodityID,
			f_heading as heading
			,parentID,
			'f' as price_type,
			concat(f_grade,', ',f_size) as size_grade
			FROM `tbl_dom_master` as m
			$where_condition   
			and f_heading<>''
			and showOnlyInSteelmint = 1
			and continue_or_discontinue <> 0
			
			union all(
				SELECT id, 
				(select itemName from tbl_region_commodity_master as cm where m.commodityID=cm.id and itemType='commodity') as category, 
				(select itemName from tbl_region_commodity_master as cm where m.subCommodityID=cm.id and itemType='commodity') as sub_category, 
				(select itemName from tbl_region_commodity_master as cm where m.subSubCommodityID=cm.id and itemType='commodity') as sub_sub_category, commodityID, subCommodityID, subSubCommodityID,
				f_heading as heading
				,parentID,	
				'f' as price_type,
				concat(f_grade,', ',f_size) as size_grade
				FROM `tbl_global_dom_master` as m
				$where_condition
				and f_heading<>''
				and showOnlyInSteelmint = 1
				and continue_or_discontinue <> 0
			)
			union all(
				SELECT id, 
				(select itemName from tbl_region_commodity_master as cm where m.commodityID=cm.id and itemType='commodity') as category, 
				(select itemName from tbl_region_commodity_master as cm where m.subCommodityID=cm.id and itemType='commodity') as sub_category,
				(select itemName from tbl_region_commodity_master as cm where m.subSubCommodityID=cm.id and itemType='commodity') as sub_sub_category, commodityID, subCommodityID, subSubCommodityID, 
				cnf_heading as heading		
				,CNF_parentID as parentID,
				'cnf' as price_type,
				concat(f_grade,', ',f_size) as size_grade
				FROM `tbl_exim_master` as m
				$where_condition  AND cnf_fob like '%CNF%'
				and cnf_heading<>''
				and showOnlyInSteelmint = 1
				and continue_or_discontinue <> 0
			
			)
			union all(
				SELECT id, 
				(select itemName from tbl_region_commodity_master as cm where m.commodityID=cm.id and itemType='commodity') as category, 
				(select itemName from tbl_region_commodity_master as cm where m.subCommodityID=cm.id and itemType='commodity') as sub_category,
				(select itemName from tbl_region_commodity_master as cm where m.subSubCommodityID=cm.id and itemType='commodity') as sub_sub_category, commodityID, subCommodityID, subSubCommodityID, 
				fob_heading as heading
				,FOB_parentID parentID,
				'fob' as price_type,
				concat(f_grade,', ',f_size) as size_grade
				FROM `tbl_exim_master` as m
				$where_condition  AND cnf_fob like '%FOB%'
				and fob_heading<>''
				and showOnlyInSteelmint = 1
				and continue_or_discontinue <> 0
			
			)
			Order By
			case 
				when category='Iron Ore' then 1
				when category='Coal' then 2
				when category='Scrap & Metallics' then 3
				when category='Steel' then 4
				when category='Ferro Alloy' then 5
				when category='Ship Breaking' then 6
				else 99
			end,
			case 
				when sub_category='Non Coking' then 1
				when sub_category='Coking' then 2
				when sub_category='Met Coke' then 3
				
				when sub_category='Sponge Iron' then 1
				when sub_category='Pig Iron' then 2
				when sub_category='Melting Scrap' then 3
				when sub_category='Mill Scale' then 4
				
				when sub_category='Manganese Ore' then 1
				when sub_category='Chrome Ore' then 2
				when sub_category='Silico Manganese' then 3
				when sub_category='Ferro Manganese' then 4
				when sub_category='Ferro Chrome' then 5
				when sub_category='Ferro Silicon' then 6
				when sub_category='Ferro Moly' then 7
				when sub_category='Ferro boron' then 8
				
				when sub_category='Semi Finished' then 1
				when sub_category='Finish long' then 2
				when sub_category='Finish Flat' then 3
				
				else 99
			end,
			case 
				when sub_sub_category='Rebar' then 1
				when sub_sub_category='Structure' then 2
				when sub_sub_category='Wire Rod' then 3
				
				when sub_sub_category='HRC' then 1
				when sub_sub_category='CRC' then 2
				when sub_sub_category='HR Plate' then 3
				when sub_sub_category='PPGI' then 4
				when sub_sub_category='GP' then 5
				
				when sub_sub_category='Billet/Bloom/Ingot' then 1
				else 99
			end
			";//order by commodityID, subCommodityID , subSubCommodityID, parentID
			
		//echo $_sql;	
		$qry =mysql_query($_sql)or die(mysql_error().'<pre>'.$_sql.'</pre>');

		$itemList=array();
		$_category ='';
		$_sub_category ='';
		$relation_id_arr = array();
		$cat_arr = array();
		$new_res_arr = array();
		while($row = mysql_fetch_assoc($qry))
		{							
			$relation_id = (int)$row['id'];	
			$relation_id_arr[]=$relation_id;
			$row['heading'] = $row['heading'].', '.$row['size_grade']; 
			if($row['parentID']==$relation_id)
				$itemList[$row['commodityID']][$row['subCommodityID']][$row['subSubCommodityID']]['parentID'][$relation_id] = array(trim($row['heading'],','), $row['price_type']);
			else
				$itemList[$row['commodityID']][$row['subCommodityID']][$row['subSubCommodityID']]['child'][$row['parentID']][$relation_id] = array(trim($row['heading'],','), $row['price_type']);
			//$result[]=$itemList;
			$cat_arr[$row['commodityID']] = $row['category'];	
			$cat_arr[$row['subCommodityID']] = $row['sub_category'];	
			$cat_arr[$row['subSubCommodityID']] = $row['sub_sub_category'];	
			
			if($row['parentID']>0){
				$new_res_arr['parentID'][$row['parentID']][$relation_id][$row['price_type']] =  array(
											"id"  =>  $relation_id,
											"value"  =>  trim($row['heading'],','),
											"priceType"  =>  $row['price_type'],
											"type"  =>  'child'
										); /* 
				$new_res_arr['parentID'][$row['parentID']][$row['price_type']] = array(
											"id"  =>  $relation_id,
											"value"  =>  trim($row['heading'],','),
											"priceType"  =>  $row['price_type'],
											"type"  =>  'parent'
										); */
			}
			
			{			
				$new_res_arr['child'][$relation_id][$row['price_type']] = array(
											"id"  =>  $relation_id,
											"value"  =>  trim($row['heading'],','),
											"priceType"  =>  $row['price_type']											
										);
			}
			
			//$new_list_arr[$row['commodityID']][$row['subCommodityID']][$row['subSubCommodityID']] =  $relation_id;
			//$new_list_arr[$row['commodityID']][$row['subCommodityID']][$row['subSubCommodityID']][$relation_id][$row['price_type']] =  $relation_id;
			/* 
			if($row['parentID']>0){
				$childOF[$row['parentID']][] =  $relation_id;
			}else{
				$parentIDS[$relation_id] = $row['parentID'];
			}
			 */
			$new_list_arr[$row['commodityID']][$row['subCommodityID']][$row['subSubCommodityID']][$row['parentID']][$relation_id][$row['price_type']] =  $relation_id;
		}
		
		$dropdownValues=array();
		///$item=array();
		foreach($new_list_arr as $commodityID=>$commodity_arr){
			$item=array();
			$item["id"]  =  (int)$commodityID;
			$item["type"]  =  "Commodity";
			$item["value"]  =  $cat_arr[$commodityID];
			
			//$scItem=array();
			foreach($commodity_arr as $subCommodityID=>$sub_commodity_arr){
				$scItem=array();
				$scItem["id"]  =  (int)$subCommodityID;
				$scItem["value"]  =  $cat_arr[$subCommodityID];				
				$scItem["type"]  =  'subCommodity';	
				$sccItem=array();
				foreach($sub_commodity_arr as $subSubCommodityID=>$_rel_id_arr){
					
					$SizeORGrades=array();
					foreach($_rel_id_arr[0] as $_rel_id=>$price_type_arrprice_type_arr){							
						foreach($new_res_arr['child'][$_rel_id] as $price_type=>$price_type_arr){
							$price_type_arr['type']='parent';
							
							if(isset($_rel_id_arr[$_rel_id])){
								$SizeORGradesChild=array();
								//foreach($_rel_id_arr[$_rel_id] as $_rel_id_child=>$price_type_arrprice_type_arr_child){							
									foreach($new_res_arr['parentID'][$_rel_id] as $price_type_child=>$price_type_arr_child_arr){
										//$price_type_arr_child['type']='child'; 
										foreach($price_type_arr_child_arr as $child_price_type=>$price_type_arr_child)
											$SizeORGradesChild[] = $price_type_arr_child;
									}
								//}
								
								$price_type_arr['child']=$SizeORGradesChild; 
							}
							
							$SizeORGrades[] = $price_type_arr;
						}						
					}
					
					
					
					
					if($subSubCommodityID==0){
						// print_r($_rel_id);echo '<br>';
						
						//$scItem["SizeORGrades"][] = $SizeORGrades;
						$scItem["SizeORGrades"] = $SizeORGrades;
					}else{
						//$sccItem=array();
						$sccItem["id"]  =  (int)$subSubCommodityID;
						$sccItem["value"]  =  $cat_arr[$subSubCommodityID];				
						$sccItem["type"]  =  'subSubCommodity';	
						
						//$sccItem["SizeORGrades"][] = $SizeORGrades;
						$sccItem["SizeORGrades"] = $SizeORGrades;
						
						$scItem["subSubCommodity"][] = $sccItem;
					}
				}
				
				///$scItem["subSubCommodity"][] = $sccItem;
				
				$item["subCommodity"][] = $scItem;
			}
			
			$dropdownValues[] = $item;
		}
		$result['dropdownValues'] = $dropdownValues;
		//print_r($dropdownValues);
		///die;
		/* foreach($itemList as $_category=>$_catArr){
			$item=array();
			$item["id"]  =  $_category;
			$item["type"]  =  "Commodity";
			$item["value"]  =  $cat_arr[$_category];
			foreach($_catArr as $_sub_category=>$_sub_catArr){
				$scItem=array();
				$scItem["id"]  =  $_sub_category;
				$scItem["value"]  =  $cat_arr[$_sub_category];				
				$scItem["type"]  =  'subCommodity';	
				
				foreach($_sub_catArr as $sub_sub_category=>$sub_sub_catArr){
					//echo $sub_sub_category.'-'.$_sub_category.'-'.$_category.'<br>';
					if($sub_sub_category>0){//3rd level
					//print_r($_sub_catArr);
						$sccItem=array();
						$sccItem["id"]  =  $sub_sub_category;
						$sccItem["value"]  =  $cat_arr[$sub_sub_category];				
						$sccItem["type"]  =  'subSubCommodity';				
						///   ////
						$sccItemCitySizeGrade = array();
						foreach($sub_sub_catArr['parentID'] as $_relation_id=>$f_heading){
							$sccItemCitySizeGrade = array(
														"id"  =>  $_relation_id,
														"value"  =>  $f_heading[0],
														"priceType"  =>  $f_heading[1],
														"type"  =>  'parent'
													);
							$sccItemCitySizeGradeChild = array();
							foreach($sub_sub_catArr['child'][$_relation_id] as $c_relation_id=>$f_heading){
								$sccItemCitySizeGradeChild[] = array(
														"id"  =>  $c_relation_id,
														"value"  =>  $f_heading[0],
														"priceType"  =>  $f_heading[1],
														"type"  =>  'child'
													);
							}
							$sccItemCitySizeGrade['child'] = $sccItemCitySizeGradeChild;
							
							$sccItem['SizeORGrades'][] = $sccItemCitySizeGrade;
						}
						
						//$sccItem['SizeORGrades'][] = $sccItemCitySizeGrade;
						$scItem['subSubCommodity'][][$sub_sub_category] = $sccItem;
						//$item["subCommodity"][] = $scItem ;
					}else{
						$sccItemCitySizeGrade = array();
						foreach($sub_sub_catArr['parentID'] as $_relation_id=>$f_heading){
							$sccItemCitySizeGrade = array(
														"id"  =>  $_relation_id,
														"value"  =>  $f_heading[0],
														"priceType"  =>  $f_heading[1],
														"type"  =>  'parent'
													);
							$sccItemCitySizeGradeChild = array();
							foreach($sub_sub_catArr['child'][$_relation_id] as $c_relation_id=>$f_heading){
								$sccItemCitySizeGradeChild[] = array(
														"id"  =>  $c_relation_id,
														"value"  =>  $f_heading[0],
														"priceType"  =>  $f_heading[1],
														"type"  =>  'child'
													);
							}
							$sccItemCitySizeGrade['child'] = $sccItemCitySizeGradeChild;
							$scItem['SizeORGrades'][] = $sccItemCitySizeGrade; 
						}						
						//$scItem['SizeORGrades'][] = $sccItemCitySizeGrade; 
						///$item["subCommodity"][] = $scItem;
					}
					
					$item["subCommodity"][] = $scItem;
				}
			}
			
			$result['dropdownValues'][]=$item;
		} */
		
		///$relation_id_arr = array_unique($relation_id_arr);
		/* if(!empty($relation_id_arr)){
			$condition = "relation_id IN (". implode(',', $relation_id_arr) .")";
			$dateRange = getDateRange($section,$condition);
			$result['dateRange']=$dateRange;
		} */
		
		$user = new User($memid, $appType);
		$isAccessible =  $user->isAccessible($resourceType, $section='Tenders');
		
		if(!empty(Session::get('sectionFromDate'))){			
			$sectionFromDate = Session::get('sectionFromDate');
			$sectionTodate = Session::get('sectionTodate');			
		}else{
			$sectionFromDate = $GLOBALS['currDate'];
			$sectionTodate = $GLOBALS['currDate'];
		}
	
	if($deviceType=='ios'){
	//if(1){
		$result['dateRange'] = getDateRangeByTwoDates($sectionFromDate,$sectionTodate);
		
		/* $result['dateRange']= array(
    
					 "monthly"=> array(
					 array(
					  "key" => "jan - 2018",
					  "value" => "jan 2018"
					 ),
					 array(
					  "key" => "feb - 2018",
					  "value" => "feb 2018"
					 ),
					 array(
					  "key" => "mar - 2018",
					  "value" => "mar 2018"
					 ),
					 array(
					  "key" => "apr - 2018",
					  "value" => "apr 2018"
					 ),
					 array(
					  "key" => "jun - 2018",
					  "value" => "jun 2018"
					 ),
					 array(
					  "key" => "jul - 2018",
					  "value" => "jul 2018"
					 ),
					 array(
					  "key" => "aug - 2018",
					  "value" => "aug 2018"
					 ),
					 array(
					  "key" => "sep - 2018",
					  "value" => "sep 2018"
					 ),
					 array(
					  "key" => "oct - 2018",
					  "value" => "oct 2018"
					 ),
					 array(
					  "key" => "nov - 2018",
					  "value" => "nov 2018"
					 ),
					 array(
					  "key" => "dec - 2018",
					  "value" => "dec 2018"
					 ),
					 array(
					  "key" => "jan - 2019",
					  "value" => "jan 2019"
					 ),
					 array(
					  "key" => "feb - 2019",
					  "value" => "feb 2019"
					 ),
					 array(
					  "key" => "mar - 2019",
					  "value" => "mar 2019"
					 ),
					 array(
					  "key" => "apr - 2019",
					  "value" => "apr 2019"
					 ),
					 array(
					  "key" => "may - 2019",
					  "value" => "may 2019"
					 ),
					 array(
					  "key" => "jun - 2019",
					  "value" => "jun 2019"
					 )

					),
					 "quarterly" => array(
					  array(
					  "key" => "Q1 2018",
					  "value" => "Q1-2018"
					 ),
					  array(
					  "key" => "Q2 2019",
					  "value" => "Q2-2018"
					 ),
					  array(
					  "key" => "Q3 2019",
					  "value" => "Q3-2018"
					 ),
					  array(
					  "key" => "Q4 2019",
					  "value" => "Q4-2018"
					 ),
					  array(
					  "key" => "Q1 2019",
					  "value" => "Q1-2019"
					 ),
					  array(
					  "key" => "Q2 2019",
					  "value" => "Q2-2019"
					 ) 
					),

					 "yearly" => array(
					  array(
					  "key" => "2010",
					  "value" => "2010"
					 ),
					  array(
					  "key" => "2011",
					  "value" => "2011"
					 ),
					  array(
					  "key" => "2012",
					  "value" => "2012"
					 ),
					  array(
					  "key" => "2013",
					  "value" => "2013"
					 ),
					  array(
					  "key" => "2014",
					  "value" => "2014"
					 ),
					  array(
					  "key" => "2015",
					  "value" => "2015"
					 ),
					  array(
					  "key" => "2016",
					  "value" => "2016"
					 ),
					  array(
					  "key" => "2017",
					  "value" => "2017"
					 ),
					  array(
					  "key" => "2018",
					  "value" => "2018"
					 ),
					  array(
					  "key" => "2019",
					  "value" => "2019"
					 )

					) 

				  ); */
	}else{
		$result['dateRange']= array(
			"format" 	=>array(
							"yearly"=>"Yearly",
							"monthly"=>"Monthly",
							"quarterly"=>"Quarterly"
						),
			"fromDate" 	=>$sectionFromDate,
			"toDate" 	=>$sectionTodate
		);
	}
		/* if($type=='default'){//
			//json file $result;
		} */
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $result;
	}
	
	public static function getPricesFilter($section='prices', $tradeType='Domestic', $regionID=0, $appType='SM'){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$result = array();
		switch(strtolower($section)){
			case "prices":
			case "price":
				$where_condition=" WHERE category<>'INDEX' ";
				switch($tradeType){
					case "Domestic":
					case "DOM":						
						$heading_col = "f_heading";
						$table_name = "tbl_dom_master";
						$where_condition.=" AND f_heading<>'' ";
						if($regionID)
							$where_condition.=" AND regionID='$regionID' ";
						/*if($regionID){
							//$where_condition.=" AND regionID='$regionID' ";
							$where_condition.=" AND sc.country_id='$regionID' ";
							$left_join = " left outer join tbl_state_city sc ON sc.ID = m.cityID";
						}*/
					break;
					case "Import":
					case "CNF":
						$heading_col = "cnf_heading";
						$table_name = "tbl_exim_master";
						$where_condition.=" AND cnf_heading<>'' ";
						$where_condition.=" AND cnf_fob like '%CNF%'";
						if($regionID)
							$where_condition.=" AND CNF_regionID='$regionID' ";
					break;
					case "Export":
					case "FOB":
						$heading_col = "fob_heading";
						$table_name = "tbl_exim_master";
						$where_condition.=" AND fob_heading<>'' ";
						$where_condition.=" AND cnf_fob like '%FOB%'";		
						if($regionID)
							$where_condition.=" AND FOB_regionID='$regionID' ";
					break;
				}
			break;
		}
		/* if($_sql==''){
			return $result;
		}
		 */
				 
		//$_sql = "SELECT id, upper(`sub_category`) as sub_category, upper(category) as category, 
		$_sql = "SELECT id, 
			(select itemName from tbl_region_commodity_master as cm where m.commodityID=cm.id and itemType='commodity') as category, 
			(select itemName from tbl_region_commodity_master as cm where m.subCommodityID=cm.id and itemType='commodity') as sub_category, commodityID, subCommodityID,
		   $heading_col			
		   FROM `$table_name` as m
		   $where_condition
		   
		   group by commodityID, subCommodityID , f_size, f_grade
		   order by case category	
				when 'IRON ORE' then 1
				when 'COAL' then 2
				when 'SCRAP' then 3
				when 'SHIP BREAKING' then 4
				when 'SEMI FINISHED' then 5
				when 'FINISH LONG' then 6					
				when 'FINISH FLAT' then 7
				when 'FERRO ALLOY' then 8											
				else 99
			end,  case sub_category	
				when 'IRON ORE' then 1
				when 'PELLETS' then 2
				when 'COAL' then 3
				when 'SCRAP' then 4
				when 'SPONGE IRON' then 5
				when 'SPONGE PELLET' then 6
				when 'INGOT' then 7
				when 'BILLET' then 8
				when 'PIG IRON' then 9
				when 'TMT' then 10
				when 'REBAR' then 10
				when 'STRUCTURE' then 11
				when 'WIRE ROD' then 12
				when 'PIPES' then 12
				when 'HRC' then 13
				when 'CRC' then 14
				when 'HR PLATE' then 15
				when 'MANGANESE_ORE' then 16
				when 'CHROME_ORE' then 17
				when 'SILICO MANGANESE' then 18
				when 'FERRO MANGANESE' then 19
				when 'FERRO SILICON' then 20
				when 'FERRO CHROME' then 21
														
				else 99 
			end	,
			 f_size, f_grade
			";
		/*  echo '<pre>';
			print_r($_sql);
		echo '<pre>';  */
		$qry =mysql_query($_sql)or die(mysql_error().'<pre>'.$_sql.'</pre>');

		$itemList=array();
		$_category ='';
		$_sub_category ='';
		$relation_id_arr = array();
		$cat_arr = array();
		while($row = mysql_fetch_assoc($qry))
		{							
			$relation_id = $row['id'];	
			$relation_id_arr[]=$relation_id;
			//$itemList[$row['category']][$row['sub_category']][$relation_id] = $row[$heading_col];
			$itemList[$row['commodityID']][$row['subCommodityID']][$relation_id] = trim($row[$heading_col],',');
			//$result[]=$itemList;
			$cat_arr[$row['commodityID']] = $row['category'];	
			$cat_arr[$row['subCommodityID']] = $row['sub_category'];	
		}
		
		foreach($itemList as $_category=>$_catArr){
			$item=array();
			$item["id"]  =  $_category;
			$item["type"]  =  "Commodity";
			$item["value"]  =  $cat_arr[$_category];
			foreach($_catArr as $_sub_category=>$_sub_catArr){
				$scItem=array();
				$scItem["id"]  =  $_sub_category;
				$scItem["value"]  =  $cat_arr[$_sub_category];				
				$scItem["type"]  =  'subCommodity';				
				///   ////
				$scItemCitySizeGrade = array();
				foreach($_sub_catArr as $_relation_id=>$f_heading){
					$scItemCitySizeGrade[] = array(
												"id"  =>  $_relation_id,
												"value"  =>  $f_heading,
												"type"  =>  'SizeORGrades'
											);
				}
				$scItem['SizeORGrades'] = $scItemCitySizeGrade;
				$item["subCommodity"][] = $scItem;
			}
			
			$result['dropdownValues'][]=$item;
		}
		
		$relation_id_arr = array_unique($relation_id_arr);
		if(!empty($relation_id_arr)){
			$condition = "relation_id IN (". implode(',', $relation_id_arr) .")";
			$dateRange = getDateRange($section,$condition);
			$result['dateRange']=$dateRange;
		}
		/* if($type=='default'){
			//json file $result;
		} */
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $result;
	}
	
    public static function getPricesSearchRows($sterm, $sectionType, $filter=array()){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$implode = array();
		
		if(isset($filter['sterm'])){
			$sterm = $filter['sterm'];
		}elseif(isset($filter['searchTerms'])){
			$sterm = $filter['searchTerms'];
		}
		
		$words = explode(' ', trim(preg_replace('/\s+/', ' ', $sterm)));
		$othercond = " AND showOnlyInSteelmint  =1 AND continue_or_discontinue <> 0";
		
		if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
			$othercond .= " AND (";
				$othercond .= " `commodityID` IN (";
				$othercond .= implode(", ", $filter['commodityID']);
				$othercond .= ")";
			$othercond .= " OR ";	
				$othercond .= " `subCommodityID` IN (";
				$othercond .= implode(", ", $filter['commodityID']);
				$othercond .= ")";
			$othercond .= " OR ";	
				$othercond .= " `subSubCommodityID` IN (";
				$othercond .= implode(", ", $filter['commodityID']);
				$othercond .= ")";
			$othercond .= ")";
		}
		
		foreach ($words as $word) {
			$implode_dom[] = "
			CONCAT(
				chemical_composition,
				delivery_terms,
				f_grade,
				f_size,
				city,
				state,
				supplier,
				region,
				payment,
				quantity,
				delivery_period,
				taxes,
				currency,
				day_update,
				publication_day_time,
				f_heading,
				commodty_name,
				sub_commodty_name,
				sub_sub_commodty_name
			)  
			LIKE '%" . mysql_real_escape_string($word) . "%'";
		}
        
		foreach ($words as $word) {
			$implode_exim[] = "
			CONCAT(
				chemical_composition,
				delivery_terms,
				f_grade,
				f_size,
				payment,
				quantity,
				delivery_period,
				taxes,
				currency,
				day_update,
				publication_day_time,
				FOB_heading,
				CNF_heading,
				load_country,
				load_port,
				unload_country,
				unload_port,
				commodty_name,
				sub_commodty_name,
				sub_sub_commodty_name
			)  LIKE '%" . mysql_real_escape_string($word) . "%'";
		}
		
		if (count($implode_dom) > 0){
			$q_dom = " " . implode(" AND ", $implode_dom) . "";
		}
		if (count($implode_dom) > 0){
			$q_exim = " " . implode(" AND ", $implode_exim) . "";
		}
		
        $sql = "select  title,
                        size_grade,
                        date_time,
                        assessment,
                        flag,
                        relation_id,
                        f_cnf_fob
                FROM    tbl_price_static        
                WHERE   relation_id IN (
                    select  id
                    from    tbl_dom_master 
                    where   $q_dom
					$othercond
                ";    
		if( "indiaprice" != strtolower($sectionType)){
			$sql .=  "          UNION
						
						select  id
						from    tbl_global_dom_master 
						where   $q_dom
						$othercond
						
						UNION
						
						select  id
						from    tbl_exim_master 
						where   $q_exim
						$othercond
					
				";			
		} 
        $sql .= ")";
		
		if(isset($filter['tradeType']) && !empty($filter['tradeType'])){
			if(strtolower($filter['tradeType'])=='import' || strtolower($filter['tradeType'])=='cnf')
				$tradeType='cnf';
			elseif(strtolower($filter['tradeType'])=='export' || strtolower($filter['tradeType'])=='fob')
				$tradeType='fob';
			else
				$tradeType='f';
			
			$sql .= " AND f_cnf_fob='".$tradeType."'";
		}
		
		if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
			if(is_array($filter['regionID'])){
				$sql .= " AND (`regionID` IN (" . implode(',',$filter['regionID']) .") OR `countryID` IN (" . implode(',',$filter['regionID']) ."))"; 
			}else{
				$sql .= " AND (";
				$sql .= " (regionID = " .  $filter['regionID']." OR countryID = ".$filter['regionID'].")";
				$sql .= ")";
			}
		}
		
		$sql.=" ORDER BY f_order_by, parentID ";
		
        if(isset($filter['debug']) && $filter['debug'] == 1) {
			echo "sql:", $sectionType, $sql , "<br />";
		}
		$rs = mysql_query($sql);
		$result = array();
		$prices = array();
		while($row = mysql_fetch_array($rs)){
            $result['title'] = $row['title'];
            $result['size_grade'] =  $row['size_grade'];
            $result['date_time'] =  $row['date_time'];
            $result['assessment'] =  $row['assessment'];
			$result["flag"] = "https://www.steelmint.com/steeladmin/flags/".strtolower($row['flag']).".png";
            $result['relation_id'] =  $row['relation_id'];
            $result['f_cnf_fob'] =  $row['f_cnf_fob'];		    
            $prices[] = $result;
        }
        //include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $prices;
    }	

	public static function getPricesRowsCnt($filter=array()){
		$startdate = $filter['fromdate'];
		$enddate = $filter['todate'];
		$rids = $filter['prices_assessments_to_show'];
		$considerTableName = $filter['considerTableName'];
		
		$whrCond = '';
		if( '' != $rids )
		    $whrCond = " and `relation_id` in (" . $rids . ")  ";

        if( 'tbl_price_static' == $considerTableName ){
    		return qryToCommaSepString("
    			SELECT count(*) as cnt
    			FROM `$considerTableName` 
    			WHERE DATE(date_added) >= '$startdate'
    			and  DATE(date_added) <=  '$enddate'
    			$whrCond
    		");
        } else {
            
    		return qryToCommaSepString("
    			SELECT count(*) as cnt
    			FROM `$considerTableName` 
    			WHERE DATE(date_time_formatted) >= '$startdate'
    			and  DATE(date_time_formatted) <=  '$enddate'
    			$whrCond
    			and isAssessmentUpdated = 'Y'
    		");
        }
		
	}
	public static function getPricesRowsVendorAPI($fromdate='',$todate='',$commodityIDSubscribedTo='',$prices_assessments_to_show='',$commodityIDFilter='',$regionIDFilter='',$considerTableName='tbl_price_static',$consider_all_assessments='n',$appType='SM')
	{
        $result=array();
		$f_order_by_col='f_order_by';
		if($appType=='CM')
			$f_order_by_col='f_order_by_cm';		
		$continue_or_discontinue=1;
		$prices_assessments_to_show_cnt=0;
		$sql = "SELECT a.`relation_id`,";		
		$sql .= "	a.`title`,b.`commodity`,b.`sub_commodity`,b.`sub_sub_commodity`,a.`size_grade`,a.`price`,
					a.`commodityID`,
					a.`subCommodityID`,
					a.`subSubCommodityID`,
					a.`regionID`, 
					a.`date_time_formatted`,
					a.`change`, 
		            a.`1W`, 
					a.`1M`, 
					a.`3M`, 
					a.`min_price`, 
					a.`max_price`, 
					a.`sentiments`,
					b.`currency`, 
					b.`t_frequency`,
					CASE WHEN b.`trade_type` = 'EXIM' THEN
							CASE WHEN b.`cnf_fob` = 'cnf' THEN b.`cnf_countryId_name`
							ELSE b.`fob_countryId_name`
							END
					ELSE b.`countryId_name`
					END as countryName";
		$sql .= " FROM `" . $considerTableName . "` a";
		$sql .= " INNER JOIN `tbl_op_commodity_master` b ON a.`relation_id` = b.`id` where b.`continue_or_discontinue` = 1 and b.`heading_flag` = 'Y' and date_format(date_time_formatted,'%y %m %d %h') = date_format(date_added,'%y %m %d %h') ";
		$sql .= " AND DATE(date_time_formatted) >= '" . $fromdate . "'";
		$sql .= " AND DATE(date_time_formatted) <= '" . $todate . "'";
		
		if($appType=='SM')
			$sql.= " and b.showOnlyInSteelmint = 1";
		elseif($appType=='CM')
			$sql.= " and a.commodityID = 401";
		if($commodityIDFilter!='')				
			$sql.= " and (a.commodityID in (".$commodityIDFilter.") or a.subCommodityID in (".$commodityIDFilter.") or a.subSubCommodityID in (".$commodityIDFilter."))";
			
		if($commodityIDSubscribedTo!='')				
			$sql.= " and (a.commodityID in (".$commodityIDSubscribedTo.") or a.subCommodityID in (".$commodityIDSubscribedTo.") or a.subSubCommodityID in (".$commodityIDSubscribedTo."))";
		
		if($regionIDFilter!='')				
			$sql.= " and a.regionID in (".$regionIDFilter.")";
		
		if($consider_all_assessments!='y' && $prices_assessments_to_show !='')				
			$sql.= " and b.id in (".$prices_assessments_to_show.")";
		$sql.= " order by ".$f_order_by_col;
		//echo $sql;
		//die;
		$query = mysql_query($sql);
		while($row = mysql_fetch_assoc($query)){
			$currencySymbolDefault = preg_replace('#[a-z0-9.]*#i', '',$row['price']);
			$_price = trim(str_replace(",","",strip_tags($row['price'])),$currencySymbolDefault);
			$_change = str_replace("&nbsp;", "", strip_tags(trim(preg_replace("/\r|\n/", "", $row['change']))));
			$_change = str_replace(',', '', $_change);
			$strtrarr = array(" " => "");
			$_changeValue = strtr($_change, $strtrarr);
			$_1w = trim(str_replace(",","",strip_tags($row['1W'])),$currencySymbolDefault);
			$_1m = trim(str_replace(",","",strip_tags($row['1M'])),$currencySymbolDefault);
			$_3m = trim(str_replace(",","",strip_tags($row['3M'])),$currencySymbolDefault);
			$_min = trim(str_replace(",","",strip_tags($row['min_price'])),$currencySymbolDefault);
			$_max = trim(str_replace(",","",strip_tags($row['max_price'])),$currencySymbolDefault);
			$result['ID'] = intval($row['relation_id']);
			$result['Title'] = $row['title'];
			$result['GradeSize'] = $row['size_grade'];
			$result['Commodity'] = $row['commodity'];
			$result['SubCommodity'] = $row['sub_commodity'];
			$result['SubSubCommodity'] = $row['sub_sub_commodity'];
			$result['CommodityID'] = $row['commodityID'];
			$result['SubCommodityID'] = $row['subCommodityID'];
			$result['SubSubCommodityID'] = $row['subSubCommodityID'];
			//$result['RegionID'] = $row['regionID'];
			$result['CountryName'] = $row['countryName'];
			$result['PublishedDateTime'] = $row['date_time_formatted'];
			$result['Price'] = $_price;
			$result['Change'] = $_changeValue;
			$result['1W'] = $_1w;
			$result['1M'] = $_1m;
			$result['3M'] = $_3m;
			$result['MinPrice'] = $_min;
			$result['MaxPrice'] = $_max;
			$result['Sentiments'] = $row['sentiments'];
			$result['Currency'] = $row['currency'];
			$result['Frequency'] = $row['t_frequency'];
			$data[]=$result;
		}
		return $data;
    }
	
	public static function getNewsRowsVendorAPI($fromdate='',$todate='',$commodityIDFilter='',$regionIDFilter='',$appType='SM',$api_key='')
	{
        $result=array();
		$sql = "SELECT 'Insight' as type,";		
		$sql .= "	a.`post_date`,a.`post_time`,a.`post_title`,a.`post_content`,a.`image`,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = a.commodityId) as commodityName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = a.subCommodityId) as subCommodityName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = a.subSubCommodityID) as subSubCommodityName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'region' and `ID` = a.regionId) as regionName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'region' and `ID` = a.continentID) as continentName,
					a.`commodityId`,
					a.`subCommodityId`,
					a.`subSubCommodityID`,
					a.`regionId`, 
					a.`continentID`";
		$sql .= " FROM tbl_news_post a";
		$sql .= " where post_date >= '" . $fromdate . "'";
		$sql .= " AND post_date <= '" . $todate . "'";
		
		if($appType=='SM')
			$sql.= " and for_smgroup_company like '%steelmint.com%'";
		elseif($appType=='CM')
			$sql.= " and for_smgroup_company like '%coalmint.com%'";
		if($commodityIDFilter!='')				
			$sql.= " and (a.commodityId in (".$commodityIDFilter.") or a.subCommodityId in (".$commodityIDFilter.") or a.subSubCommodityID in (".$commodityIDFilter."))";
			
		if($regionIDFilter!='')				
			$sql.= " and a.regionId in (".$regionIDFilter.")";
		// if($api_key == 'qkoeI6XB7YZhxupVE2Oe93')
			// $sql.=" limit 2";
		$sql.=" union ";
		
		$sql .= "SELECT 'Intel' as type,";		
		$sql .= "	date(a.`datePublished`) as post_date,time(a.`datePublished`) as post_time,a.`title` as post_title,a.`description` as post_content,a.`imageUrl` as image,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = a.commodityID) as commodityName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = a.subCommodityID) as subCommodityName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = a.subSubCommodityID) as subSubCommodityName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'region' and `ID` = a.regionID) as regionName,
					(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'region' and `ID` = a.continentID) as continentName,
					a.`commodityID` as commodityId,
					a.`subCommodityID` as subCommodityId,
					a.`subSubCommodityID` as subSubCommodityID,
					a.`regionID` as regionId, 
					a.`continentID`";
		$sql .= " FROM intel a";
		$sql .= " where date(datePublished) >= '" . $fromdate . "'";
		$sql .= " AND date(datePublished) <= '" . $todate . "'";
		
		if($appType='SM')
			$sql.= " and for_smgroup_company like '%steelmint.com%'";
		elseif($appType='CM')
			$sql.= " and for_smgroup_company like '%coalmint.com%'";
		if($commodityIDFilter!='')				
			$sql.= " and (a.commodityID in (".$commodityIDFilter.") or a.subCommodityID in (".$commodityIDFilter.") or a.subSubCommodityID in (".$commodityIDFilter."))";
			
		if($regionIDFilter!='')				
			$sql.= " and a.regionID in (".$regionIDFilter.")";
		
		if($api_key == 'qkoeI6XB7YZhxupVE2Oe93')
			$sql.=" limit 5";
		// echo $sql;
		// die;
		
		$query = mysql_query($sql);
		while($row = mysql_fetch_assoc($query)){
			$result['Type'] = $row['type'];
			$result['Date'] = $row['post_date'];
			$result['Time'] = $row['post_time'];
			$result['Title'] = removeMSWordattributes(html_entity_decode( stripslashes($row['post_title']), ENT_QUOTES));
			$row['post_content'] = str_replace(array("&amp;#8217;","&amp;#8216;"), "&#039;", $row['post_content']);
			$row['post_content'] = str_replace(array("#8217;","#8216;"), "&#039;", $row['post_content']);
			//convert - of MS word
			$row['post_content'] = str_replace(array("&amp;#8211;","&amp;#8212;"), "-", $row['post_content']);
			$row['post_content'] = str_replace(array("#8211;", "#8212;"), "-", $row['post_content']);			
			//convert doublequotes of MS word
			$row['post_content'] = str_replace(array("&amp;#8220;","&amp;#8221;"), "&#34;", $row['post_content']);
			$row['post_content'] = str_replace(array("#8220;", "#8221;"), "&#34;", $row['post_content']);
			$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));	
			$result['Content'] = $content;
			$result['Image'] = $row['image'];
			$result['Commodity Name'] = $row['commodityName'];
			$result['Sub Commodity Name'] = $row['subCommodityName'];
			$result['Sub Sub Commodity Name'] = $row['subSubCommodityName'];
			$result['Region Name'] = $row['regionName'];
			$result['Continent Name'] = $row['continentName'];
			$result['Commodity ID'] = $row['commodityId'];
			$result['Sub Commodity ID'] = $row['subCommodityId'];
			$result['Sub Sub Commodity ID'] = $row['subSubCommodityID'];
			$result['Region ID'] = $row['regionId'];
			$result['Continent ID'] = $row['continentID'];
			$data[]=$result;
		}
		return $data;
    }

	//DEFAULT_PRICES_LIMIT 
	public static function getPricesRows($memid=0, $source='listing', $resourceType="app", $type='default', $filter=array(), $pageType_1='post', $limit=5, $offset=0, $appType='SM', $_currency=''){
		//include_once "/home/steelmin/public_html/inc/config1.php"; 
        $result=array(); 
        $prices = array();
        $pricesT = array();
		
		$f_order_by_col='f_order_by';
		if($appType=='CM')
			$f_order_by_col='f_order_by_cm';
		
		$continue_or_discontinue=1;
		$prices_assessments_to_show_cnt=0;
		if(isset($filter['tradeType']) && strtolower($filter['tradeType'])=='futures'){
			$filter['tradeType']= 'regional';
			$filter['isFuture']= 2;
			$continue_or_discontinue= 2;
		}
		
		$f_cnf_fob='';$table = 'tbl_exim_master';$heading_col = "fob_heading";
		if(strtolower($filter['tradeType'])=='export' || strtolower($filter['priceType'])=='fob'){
			$f_cnf_fob='fob';
			$table = 'tbl_exim_master';
			$heading_col = "fob_heading";
		}elseif(strtolower($filter['tradeType'])=='import' || strtolower($filter['priceType'])=='cnf'){
			$f_cnf_fob='cnf';
			$table = 'tbl_exim_master';
			$heading_col = "cnf_heading";
		}elseif(strtolower($filter['tradeType'])=='regional' || strtolower($filter['tradeType'])=='domestic' || strtolower($filter['priceType'])=='f'){
			$f_cnf_fob='f';
			$table = 'tbl_dom_master';
			if(isset($filter['itemID']) && $filter['itemID']>=3000 && $filter['itemID'] <= 4999)
		    	$table = 'tbl_global_dom_master'; 
		    elseif(isset($filter['itemID']) && $filter['itemID']>=1001 && $filter['itemID'] <= 3000)
		        $table = 'tbl_dom_master';
		        
			/* if(isset($filter['regionID']) && $filter['regionID'] != 113)
		    	$table = 'tbl_global_dom_master'; 
		    elseif(isset($filter['regionID']) && $filter['regionID'] == 113)
		        $table = 'tbl_dom_master'; */
		        
			$heading_col = "f_heading";
		}
		
		
		/////m.`sticky_header_value`,n.`particular`,
		$sql = "SELECT m.`id`,";		
		$sql .= "	n.changeWOTag,
					m.`assessment`, 
		            m.`assessmentText`, 
					m.`chemical_composition`, 
					m.`showOnlyInSteelmint`, 
					m.`delivery_terms`, 
					m.`f_size`, 
					m.`publication_day_time`, 
					m.`payment`, 
					m.`remarks`, 
					m.`quantity`, 
					m.`delivery_period`, 
					m.`taxes`, 
					m.`currency`, 
					m.`category`, 
					m.`sticky_header_value`, 
					m.`rationale`, 
					n.`price`, 
					n.`mnthly_avg_dtls`, 
					n.`change`, 
					n.`min_price`, 
					n.`max_price`, 
					n.`size_grade`, 
					n.`origin`,  
					n.`flag`,  
					n.`1W`, 
					n.`1M`, 
					n.`3M`, 
					n.`sentiments`, 
					n.`remark`, 
					n.`date_time`, 
					n.`f_cnf_fob`,  
					n.`date_time_formatted`,  
					m.`show_in_app_mapview`,
					m.`view_more_text`,
					m.`f_methodology`,
					m.`unit_of_measurement`,
					m.`publication_day_time` as publicationDayTime					
					,n.`$f_order_by_col`";
		$sql .= ", CASE";
		$sql .= " WHEN m.`category` = 'LOGISTICS' THEN  m.`item`";
		$sql .= " ELSE m.`sub_category`";
		$sql .= " END as sub_category";
		$sql .= " , n.regionID as psRegionID, n.countryID";
		$sql .= " ,sc.`country_id` as regionID";
		//$sql .= " , (SELECT parentID FROM `tbl_region_commodity_master` where itemType='commodity' and ID=n.regionID) as parentRegionID";
		////$sql .= " , (SELECT parentID FROM `tbl_region_commodity_master` where itemType='commodity' and ID=sc.`country_id`) as parentRegionID";//no need
		
		
          $sql .= " ,(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = n.commodityID) as commodityName ";
		  $sql .= " ,(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = n.subCommodityID) as subCommodityName "; 
			$sql .= " ,(select itemName from tbl_region_commodity_master as cm where sc.country_id=cm.id and itemType='region') as regionName ";
		  
		
		$sql .= " ,n.commodityID, n.SubCommodityID, n.subSubCommodityID";
		$sql .= " , sc.latitude, sc.longitude, sc.zone";
		$sql .= " , n.parentID, n.title";
		
		
		/* n.`lat_long`, */
//
		if($memid) {
			$sql .= ", (SELECT COUNT(up.`id`) FROM `tbl_user_portfolio` up WHERE up.`user_id` = '" . $memid . "' AND up.`row_id` = m.`id` AND up.`type` = 'prices' and n.`f_cnf_fob`=up.`prices_col`) as portfolio";
			$sql .= ",(select id from tbl_alerts as c where c.x_days_before=n.`f_cnf_fob` and m.id=c.item_id and memid=$memid and section='price' and status='active'  limit 1) as isSetAlert";
		} else {
			$sql .= ", 0 as portfolio, '' as isSetAlert";
		}
		
		if($source=='details' && $resourceType=='web'){
			$sql .= " ,pdk.url_description  as metaDescription, pdk.url_keyword as metaKeyword";
		}
		$sql .= " ,m.f_market ";
		
		//added for NXS techies
		if($table=='tbl_exim_master')
            $sql .= " ,'' as location ";
        else
            $sql .= " ,m.city as location ";
		$sql .= " FROM `" . $table . "` m";
		$sql .= " LEFT JOIN `tbl_price_static` n ON m.`id` = n.`relation_id`";
		$sql .= " left outer join tbl_state_city sc ON sc.ID = n.cityID";
		if($source=='details' && $resourceType=='web'){
			$sql .= " left outer join tbl_price_detail_keywords pdk ON pdk.relation_id  = n.relation_id";
		}
		$sql .= " WHERE m.`id` > 0 and n.`f_cnf_fob`<>'' and m.platform like '%$resourceType%'";
		if($filter['selected_market']!=''){
            $sql .= "  and FIND_IN_SET('".$filter['selected_market']."', m.f_market) ";
		}
		
		/* if(isset($filter['innerFilterCond']) && in_array($table, array_keys($filter['innerFilterCond']))){
			$sql.= " AND " . $filter['innerFilterCond'][$table]."  ";
		} */
		if(isset($filter['innerFilterCond']) && in_array($table, array_keys($filter['innerFilterCond']))){
			$sql.= " innerFilterCond_" . $table."  ";
		}
		$orderBY = "case 
							when commodityName='Iron Ore' then 1
							when commodityName='Coal' then 2
							when commodityName='Scrap & Metallics' then 3
							when commodityName='Steel' then 4
							when commodityName='Ferro Alloy' then 5
							when commodityName='Ship Breaking' then 6
							else 99
						end,
						case 
							when subCommodityName='Semi Finished' and zone = 'NORTH INDIA' then 1
							when subCommodityName='Semi Finished' and zone = 'EAST INDIA' then 2
							when subCommodityName='Semi Finished' and zone = 'CENTRAL INDIA' then 3
							when subCommodityName='Semi Finished' and zone = 'WEST INDIA' then 4
							when subCommodityName='Semi Finished' and zone = 'SOUTH INDIA' then 5
							else 99
						end";
		
		$chkSource = true;
		
		if($source=='details'){
			$chkSource = false;
			$_source=$source;
			$source='';
			$orderBY = "";
		}
		$actualSource = $source;
		if($source!='') {//source
			
			switch($source){				
				case 'indiaPrice':
				case 'indiaprice':
					$source= '';	
					$chkSource = false;
				break;
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark'://no bookmark for prices
					$chkSource = false;
				break;
				case 'portfolio':
                    if(isset($filter['download']) &&  $filter['download']!='y'){
						$portfolio['f'] = $filter['download'];
						$portfolio['cnf'] = $filter['download'];
						$portfolio['fob'] = $filter['download'];
						$filter['download']='y';
					}else{
						$common = new Common();
						$portfolio = $common->getUserPortfolioV2019($memid, 'prices', $appType);

						if(empty($portfolio)){
							$portfolio['f'] = array(0);
							$portfolio['cnf'] = array(0);
							$portfolio['fob'] = array(0);
						}						 
					}
					$filter['itemID'] = $portfolio;
					$source= '';
					$chkSource = false;
				break;
				case 'relatedPrices':
				case 'relatedprices':
					//relatedSection
					//relatedItemID
					//"relatedItemID":119687,"relatedSection":"insight"
					$filter['commodityID'] = array(426); 
					$source= '';
					$chkSource = false;
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'keyindex':
				case 'watchlist':
					///$filter['commodityID'] = array(448); 
					///$source= '';
					$chkSource = false; 
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'recommendedPrices':
				case 'recommendedprices':
					$common = new Common();
					$cr_data = $common->getUserPortfolioV2019($memid, 'intel_insight', $appType);
					if(empty($cr_data)){
						$source= 'home';
					}else{
						$filter['commodityID'] = array(); 
						$filter['regionID'] = array();
						
						foreach($cr_data as $K=>$v){
								array_push($filter['commodityID'],$v["commodityId"]);
								array_push($filter['regionID'],$v["regionId"]);
						}
						$source= '';						
					}
				break;
				case 'recent':
				break;
				case 'alerts':
				case 'alert':
					$common = new Common();
					$alerts = $common->getUserAlertsV2019($resourceType, $memid, $type='price');

					if(empty($alerts)){
						$alerts['f'] = array(0);
						$alerts['cnf'] = array(0);
						$alerts['fob'] = array(0);
					}
					$filter['itemID'] = $alerts; 
					$source= '';
					$chkSource = false;
				break;
				case 'commodity':
				case 'commoditywise':
					$orderBY .= " ,commodityID, SubCommodityID, regionID ";
				break;
				case 'region':
				case 'regionwise':
					//$orderBY .= " , regionID, commodityID, SubCommodityID ";
					if($orderBY)
						$orderBY .= " ,regionID, commodityID, SubCommodityID ";
					else
						$orderBY .= " regionID, commodityID, SubCommodityID ";
				break;
				default: //like listing , mapview and others
					//$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
					if(isset($filter['itemIdPriceType'])):
						$itemIdPriceType = array();
						foreach($filter['itemIdPriceType'] as $itmPT):
							list($_rid, $_rtype) = explode('_', $itmPT);
							$itemIdPriceType[$_rtype][] = $_rid;
						endforeach;

						if(empty($itemIdPriceType)){
							$portfolio['f'] = array(0);
							$portfolio['cnf'] = array(0);
							$portfolio['fob'] = array(0);
						}
						$filter['itemID'] = $itemIdPriceType; 
						$source= '';
						$chkSource = false;
					endif;
					
					if( isset($filter['sliderID']) ){
						
						if($filter['sliderID']!=''){
							$common = new Common();
							
							$sliderRes = $common->getSliderDetails($filter['sliderID']);
							
							if(empty($sliderRes)){
								$slider['f'] = array(0);
								$slider['cnf'] = array(0);
								$slider['fob'] = array(0);
								
								/* $filter['commodityID'] = array(); 
								$filter['regionID'] = array(); */
							}else{
								if($sliderRes['assessmentID']){
									$slider['f'] = array($sliderRes['assessmentID']);
									$slider['cnf'] = array($sliderRes['assessmentID']);
									$slider['fob'] = array($sliderRes['assessmentID']);
									
									$filter['itemID'] = $slider;
								}
							}
						}else{
							$slider['f'] = array(0);
							$slider['cnf'] = array(0);
							$slider['fob'] = array(0);
							
							$filter['itemID'] = $slider;
						}
						
						///$source= '';
						$chkSource = false;
					}
				
					if($orderBY)
						$orderBY .= " ,parentID, date_time_formatted Desc ";
					else
						$orderBY = " ,parentID, date_time_formatted Desc ";
				break;
			}			
		}

		if(isset($filter['tabName']) && !empty($filter['tabName'])) {
			$sql .= " AND m.`tabname` like '%".$filter['tabName']."%' ";
		}
		
		if(isset($filter['price_section_type']) && !empty($filter['price_section_type'])) {
			$sql .= " AND m.`price_section_type` like '%".$filter['price_section_type']."%' ";
			//$chkSource = false;
			//added indiaprice case : remove parent child for it
			$chkSource = ($actualSource=='home' || 'portfolio'==$actualSource || 'indiaprice'==strtolower($actualSource))?false:true;
			//$chkSource = ($actualSource=='home' || 'portfolio'==$actualSource)?false:true;			
		}
		
		if(isset($filter['searchTerms']) && !empty($filter['searchTerms'])) {
			$cd = date("Y-m-d");
			$ct = date("H:i:s");
			mysql_query("
				insert into tbl_searches 
				values (
				'',
				'$cd',
				'$ct',
				$memid,
				'prices',
				'" . htmlspecialchars($filter['searchTerms'], ENT_QUOTES) . "',
				'$resourceType'
				)"
			);

			$sql .= " AND (";

			$implode = array();

			$words = explode(' ', trim(preg_replace('/\s+/', ' ', $filter['searchTerms'])));
			$words = str_replace(array("price","prices"), "", $words);
			foreach ($words as $word) {
				//if( $memid == 116707 ){
					$implode[] = '(
							n.`title` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							n.`size_grade` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`commodty_name` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`sub_commodty_name` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`sub_sub_commodty_name` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							
							m.`delivery_terms` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`chemical_composition` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`payment` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`quantity` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`delivery_period` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`taxes` REGEXP "[[:<:]]' . $word . '[[:>:]]" OR 
							m.`f_keywords` REGEXP "[[:<:]]' . $word . '[[:>:]]" )';
				/* } else {
					$implode[] = "CONCAT(n.`category`,
					n.`title`,
					n.`size_grade`,
					m.`sub_category`,
					m.`item`,				
					m.`delivery_terms`,
					m.`chemical_composition`,
					m.`payment`,
					m.`quantity`,
					m.`delivery_period`,
					m.`taxes`,
					m.`f_keywords`) LIKE '%" . mysql_real_escape_string($word) . "%'";
				}	 */		
			}

			if ($implode) {
				$sql .= " " . implode(" AND ", $implode) . "";
			}

			$sql .= ")";
			$chkSource=false;
		} 
		
		if(isset($filter['fromdate']) && $filter['fromdate'] != '') {
			$sql .= " AND DATE(date_time_formatted) >= '" . $filter['fromdate'] . "'";
			$sql .= " AND DATE(date_time_formatted) <= '" . $filter['todate'] . "'";
			
		}
		
		if(isset($filter['itemID']) && !empty($filter['itemID'])) {
			
			if(is_array($filter['itemID'])){
				$whereRowIds = array();
			
				foreach($filter['itemID'] as $_cnf_fob=>$row_ids) {
					$whereRowIds[] = "(n.`relation_id` IN (" . implode(", ", $row_ids) . ") AND n.`f_cnf_fob` = '" . $_cnf_fob . "')";
				}
				$sql .= " AND (";
				$sql .= implode(" OR ", $whereRowIds);
				$sql .= ")";
				
			}else{//for detail page
				if($f_cnf_fob)
					$sql .= " AND n.f_cnf_fob='".$f_cnf_fob."' AND n.`relation_id` = " . (int)$filter['itemID']." ";
					//$sql .= " AND n.f_cnf_fob='".$f_cnf_fob."' AND (n.`relation_id` = " . (int)$filter['itemID']." OR n.parentID=" . (int)$filter['itemID'].")";
					//$sql .= " AND n.f_cnf_fob='".$f_cnf_fob."' AND (n.`relation_id` = " . (int)$filter['itemID']." OR m.CNF_parentID=" . (int)$filter['itemID'].")";
				else
					$sql .= " AND (n.`relation_id` = " . (int)$filter['itemID']." )";
					///$sql .= " AND (n.`relation_id` = " . (int)$filter['itemID']." OR n.parentID=" . (int)$filter['itemID'].")";
					//$sql .= " AND (n.`relation_id` = " . (int)$filter['itemID']." OR m.FOB_parentID=" . (int)$filter['itemID'].")";
				/* if($f_cnf_fob)
					$sql .= " AND n.f_cnf_fob='".$f_cnf_fob."' AND n.`relation_id` = " . (int)$filter['itemID'];
				else
					$sql .= " AND n.`relation_id` = " . (int)$filter['itemID']; */
			}
		}
		
		//for 'recommendedprices'
		if(isset($cr_data) && $source==''){
			$sql .= " AND (";
			if(isset($filter['commodityID']) && !empty($filter['commodityID'])  && !in_array("709", $filter['commodityID'])) {
				
					$sql .= " n.`subCommodityID` IN (";
					$sql .= implode(", ", $filter['commodityID']);
					$sql .= ")";				
			}
			
			if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
				$regions = implode(",", $filter['regionID']); 	
				$sql .= " OR ";	
					$sql .= " sc.`country_id` IN (" . $regions;
					$sql .= ")";
			}
			
			$sql .= ")";
		}
		else{//
			if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
				$sql .= " AND (";
					$sql .= " n.`commodityID` IN (";
					$sql .= implode(", ", $filter['commodityID']);
					$sql .= ")";
				$sql .= " OR ";	
					$sql .= " n.`subCommodityID` IN (";
					$sql .= implode(", ", $filter['commodityID']);
					$sql .= ")";
				$sql .= " OR ";	
					$sql .= " n.`subSubCommodityID` IN (";
					$sql .= implode(", ", $filter['commodityID']);
					$sql .= ")";
				$sql .= ")";
			}
			$statesArray = array(710,711,712,713,714,715,716,717,718,719,720,721,722,723,724,725,726,727,728);			
			if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
				$flag = 0;	
				$rgid = implode("," , $filter['regionID']);
				if(
					strtolower($source) == "mapView" || 
					strtolower($source) == "regionwise" || 
					strtolower($source) == "regioncommoditywise" ||
					in_array($rgid, $statesArray)
				){
				//if(strtolower($source) == "mapview" || strtolower($source) == "regionwise"){
						
					if( count($filter['regionID']) > 0 and $filter['regionID'][0] == 728 ){
						$flag = 2;		
					} else {
						$rid = $filter['regionID'];
						$non_indian_state_ids = array_diff($rid,$statesArray);
						$indian_state_ids = array_intersect($rid,$statesArray);

						$s_ids = '';
						if( count($non_indian_state_ids) > 0 ){
							//$continents = implode("," , $filter['regionID']);
							$continents = implode("," , $non_indian_state_ids);
							$regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID in ($continents) OR id  in ($continents)) ");
						}		
						if( count($indian_state_ids) > 0 ){
							$indianStatesIds = implode("," , $indian_state_ids);
							$indianStatesNames = qryToCommaSepString("select statesToConsider from tbl_region_commodity_master where id IN ($indianStatesIds) ");
							$indianStatesNames = "'" . str_replace(',', "','", $indianStatesNames) . "'";
							$s_ids = "  m.state in ($indianStatesNames) ";	
						}
						
						$flag = 1;						
					}
				} else {
					$regions = implode(",", $filter['regionID']);
					$flag = 1;
				}
				if( $flag == 2 ){
					$sql .= " AND  n.`regionID` = 113 ";	
				}
				if( $flag == 1 ){
					if( $regions != '' ){
						if( $s_ids != '' ){
							$s_ids .= " or $s_ids ";
						}
						$sql .= " AND (sc.`country_id` IN (" . $regions;
							$sql .= ") $s_ids or n.`regionID` IN (" . $regions;
							$sql .= ")";
						$sql .= " )";	
					} else if( $s_ids != '' ){
						$sql .= " AND ( $s_ids ";
						$sql .= " )";	
					}
				}
			}
		}
		if(isset($filter['tradeType']) && !empty($filter['tradeType'])){
			if(is_array($filter['tradeType'])){
				if(in_array('Futures', $filter['tradeType'])!==false)
					$sql .= " AND (n.`f_cnf_fob` IN ('" . implode("','",$filter['tradeType']) ."') OR n.continue_or_discontinue=2)";
				else
					$sql .= " AND n.`f_cnf_fob` IN ('" . implode("','",$filter['tradeType']) ."')";
			}else
				$sql .= "AND n.f_cnf_fob='".$f_cnf_fob."'";
		}elseif(isset($filter['dataType']) && !empty($filter['dataType'])){
			if(is_array($filter['dataType'])){
				if(in_array('Futures', $filter['dataType'])!==false)
					$sql .= " AND (n.`f_cnf_fob` IN ('" . implode("','",$filter['dataType']) ."') OR n.continue_or_discontinue=2)";
				else
					$sql .= " AND n.`f_cnf_fob` IN ('" . implode("','",$filter['dataType']) ."')";
			}else
				$sql .= "AND n.f_cnf_fob='".$filter['dataType']."'";
		}
		
		//check if any steelmint user is logged in. if yes, show him the futures prices
		$isSteelMintUserLoggedIn = 0;
		if( $memid != 0 && $memid != '' ) {
			$usernameOfMemid = qryToCommaSepString("select concat(username,',',email,',',addtnl_email) from tbl_members where id = $memid and id <> 116707"); //chk for all records except for memid = 116707 which is anmol_platinum@steelmint.com
			if( strpos( $usernameOfMemid, "steelmint.com" ) !== false || strpos( $usernameOfMemid, "steelmintgroup.com" ) !== false ){
				$isSteelMintUserLoggedIn = 1;
			}
		}

        if(isset($filter['debug']) && $filter['debug'] == 1) {
			echo "<br /> appType:" . $appType;
			echo "<br /> isSteelMintUserLoggedIn:" . $isSteelMintUserLoggedIn;
			echo "<br /> memid:" . $memid;
			print_r($filter);
		} 

		if(isset($filter['isFuture'])){ //when user selects the option "Futures" in trade type combo box in prices page
			//$sql .= " AND n.showOnlyInSteelmint  =1 AND n.continue_or_discontinue = $continue_or_discontinue";
			$sql .= " AND n.continue_or_discontinue = $continue_or_discontinue";
		}elseif(($appType != 'CM' && $isSteelMintUserLoggedIn == 1) || 3629 == $memid)//show futures prices only to steelmint users + memid = 3629
			//$sql .= " AND n.showOnlyInSteelmint  =1 AND n.continue_or_discontinue <> 0";
			$sql .= "  AND n.continue_or_discontinue <> 0";
		elseif(in_array($memid, $GLOBALS['CM_MEMID_ALLOWED'])!==false){
			$sql .= " AND n.continue_or_discontinue <> 0 AND n.commodityID<>475 ";
		}elseif($appType == 'CM') //if coalmint, show all coal related records only
			$sql .= " AND n.continue_or_discontinue <> 0 AND n.commodityID = 401 ";
		elseif($filter["API_SM_flag"] == 'Y') //if coalmint, show all coal related records only
			$sql .= "  AND n.continue_or_discontinue = 1";
        elseif($filter["selected_market"] != '')
			$sql .= " AND n.continue_or_discontinue = 1";
		else
			$sql .= "  AND n.continue_or_discontinue = 1";
			//$sql .= " AND n.showOnlyInSteelmint  = 1 AND n.continue_or_discontinue = 1";
		
		if(isset($filter['prices_assessments_to_show']) && $filter['API_Key'] != 'QC7uuGXfMy'){
			$sql .= " AND n.isAssessmentUpdated = 'Y'";
		}
		
		$sqlTC = "select distinct currency_code, currency_symbol 
				from tbl_country
                where  section like 'price%'
                order by country
            ";
		$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);
		$symbolType['CEN'] = 'FFE0';
		while($rowTC = mysql_fetch_assoc($rsTC)){
			$symbolType[$rowTC['currency_code']] = $rowTC['currency_symbol'];
		}
		
		$currencyConvertor=1;
		
		if($source)
			$sql .= " and m.source like '%$source%'"; 
		if(isset($filter['innerFilterCond']) && $filter['innerFilterCond'] != '')
			$chkSource=false;
	
		if($chkSource && $s_ids == '' && $source != 'keyindex_cm' && $source != 'keyindex' )
			$sql.=" and n.parentID=0";
		
		
		 if(isset($filter['isNFS'])){
			$sql.=" and n.category='NON FERROUS' ";
		}
		
		$flag = 0;	
		if(isset($filter['innerFilterCond']) && !in_array('tbl_dom_master', array_keys($filter['innerFilterCond'])) && $table=='tbl_exim_master'){
			$flag = 1;
		}
		
		if($f_cnf_fob=='' && $flag == 0){//
			$sql1 = " UNION ALL (";
			
			$sql1 .= str_replace('`'.$table.'` m' , '`tbl_dom_master` m', $sql);
			
			if(isset($filter['innerFilterCond']) && in_array('tbl_dom_master', array_keys($filter['innerFilterCond']))){
				$sql1 = str_replace('innerFilterCond_'.$table , 'innerFilterCond_tbl_dom_master', $sql1);
			}
			
			$sql1 .= " ) ";
			
			$sql2 = " UNION ALL (";
			
			$sql2 .= str_replace('`'.$table.'` m' , '`tbl_global_dom_master` m', $sql);
			
			if(isset($filter['innerFilterCond']) && in_array('tbl_global_dom_master', array_keys($filter['innerFilterCond']))){
				$sql2 = str_replace('innerFilterCond_'.$table , 'innerFilterCond_tbl_global_dom_master', $sql2);
			}
			
			$sql2 .= " ) ";
			
			$sql .= $sql1;
			$sql .= $sql2;
		}elseif($f_cnf_fob=='f'){
			$sql2 = " UNION ALL (";
			if($table=='tbl_dom_master'){
				$sql2 .= str_replace('`'.$table.'` m' , '`tbl_global_dom_master` m', $sql);
				
				if(isset($filter['innerFilterCond']) && in_array('tbl_global_dom_master', array_keys($filter['innerFilterCond']))){
					$sql2 = str_replace('innerFilterCond_'.$table , 'innerFilterCond_tbl_global_dom_master', $sql2);
				}
			}else{
				$sql2 .= str_replace('`'.$table.'` m' , '`tbl_dom_master` m', $sql);
			
				if(isset($filter['innerFilterCond']) && in_array('tbl_dom_master', array_keys($filter['innerFilterCond']))){
					$sql2 = str_replace('innerFilterCond_'.$table , 'innerFilterCond_tbl_dom_master', $sql2);
				}
			}
			
			$sql2 .= " ) ";
			$sql .= $sql2;
		}
		//if($memid==56350){echo 'f_cnf_fob_'.$f_cnf_fob, $sql.'<br>---';die;}
		if(isset($filter['innerFilterCond'])){
			$chkSource = false;
			if(isset($filter['innerFilterCond']) && in_array('tbl_global_dom_master', array_keys($filter['innerFilterCond'])))
				$sql = str_replace('innerFilterCond_tbl_global_dom_master' , 'AND ('. $filter['innerFilterCond']['tbl_global_dom_master'].')', $sql);
			else
				$sql = str_replace('innerFilterCond_tbl_global_dom_master' , '', $sql);
			
			if(isset($filter['innerFilterCond']) && in_array('tbl_dom_master', array_keys($filter['innerFilterCond'])))
				$sql = str_replace('innerFilterCond_tbl_dom_master' , 'AND ('. $filter['innerFilterCond']['tbl_dom_master'].') ', $sql);
			else
				$sql = str_replace('innerFilterCond_tbl_dom_master' , '', $sql);
			
			if(isset($filter['innerFilterCond']) && in_array('tbl_exim_master', array_keys($filter['innerFilterCond'])))
				$sql = str_replace('innerFilterCond_tbl_exim_master' , 'AND ('. $filter['innerFilterCond']['tbl_exim_master'].') ', $sql);
			else
				$sql = str_replace('innerFilterCond_tbl_exim_master' , '', $sql);
		}
		
		$sort_data = array(
			'n.`sub_category`',			
		);
        //05/4/2020
        $orderBY=" $f_order_by_col, parentID ";
		
		if(isset($filter['isHeatmap'])){
			$orderBY=" changeWOTag desc, $f_order_by_col, parentID ";		
		}
		
		if(isset($filter['price_section_type']) && !empty($filter['price_section_type']) && $resourceType=='web'){
			/* $orderBY = " regionID,commodityID, SubCommodityID,$f_order_by_col "; */
			$_con1="";
			if(isset($filter['commodityID'])){				
				$_con1=" and (subCommodityID in (".implode(", ", $filter['commodityID'])." ) OR subSubCommodityID in (".implode(", ", $filter['commodityID'])." ))";
			}
			if(isset($filter['regionID'])){				
				$_con1.=" and regionID in (".implode(", ", $filter['regionID'])." )";
			}

			$f_order_by_countryID = qryToCommaSepString("SELECT n.countryID FROM `tbl_prices_sequence` as ps
								left join tbl_price_static as n ON n.relation_id=ps.relation_id
								where continue_or_discontinue=1  $_con1
								group by regionID, countryID
								order by ps.f_order_by, ps.id");
								
			$orderBY = " case 
							when commodityName='Iron Ore' then 1
							when commodityName='Coal' then 2
							when commodityName='Scrap & Metallics' then 3
							when commodityName='Steel' then 4
							when commodityName='Ferro Alloy' then 5
							when commodityName='Ship Breaking' then 6
							else 99
						end,
						 ";///FIELD(psRegionID, $f_order_by_regionID),
			if($f_order_by_countryID){
				$orderBY .=" commodityID, SubCommodityID,FIELD(countryID, $f_order_by_countryID), $f_order_by_col, parentID,
						`date_time_formatted` Desc";
			}else{
				$orderBY .=" commodityID, SubCommodityID, $f_order_by_col, parentID,
						`date_time_formatted` Desc";
			}
		}
		
		if($resourceType=='web' && strtolower($source)=='commoditywise' && !empty($filter['commodityID']) && implode(", ", $filter['commodityID']) == 410){
			$sql .= " ORDER BY 
						case 
							when subCommodityName='Sponge Iron' then 1
							when subCommodityName='Pig Iron' then 2
							when subCommodityName='Melting Scrap' then 3
							when subCommodityName='Rerolling scrap' then 4
							when subCommodityName='Mill Scale' then 5
							else 99
						end, $f_order_by_col, parentID,
						`date_time_formatted` Desc";		
		}elseif (isset($filter['sort']) && in_array($filter['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $filter['sort'];
			if(isset($filter['order']))
				$sql .= " " . $filter['order'];
		}elseif($orderBY!=''){
			$sql .= " ORDER BY 
						
						" . $orderBY;
		}elseif($_source!='details'){
			
			$sql .= " ORDER BY 
						case 
							when commodityName='Iron Ore' then 1
							when commodityName='Coal' then 2
							when commodityName='Scrap & Metallics' then 3
							when commodityName='Steel' then 4
							when commodityName='Ferro Alloy' then 5
							when commodityName='Ship Breaking' then 6
							else 99
						end,
						case 
							when subCommodityName='Semi Finished' and zone = 'NORTH INDIA' then 1
							when subCommodityName='Semi Finished' and zone = 'EAST INDIA' then 2
							when subCommodityName='Semi Finished' and zone = 'CENTRAL INDIA' then 3
							when subCommodityName='Semi Finished' and zone = 'WEST INDIA' then 4
							when subCommodityName='Semi Finished' and zone = 'SOUTH INDIA' then 5
							else 99
						end,
						`date_time_formatted` Desc";
		}

        $rowsCnt = 0;
        //if APi called from new dashborad on steelmint site and its the 1st page then send count of total records.
        //if APi called from new dashborad on steelmint site then send 10 records
        if(isset($filter['renderAt']) && $filter['renderAt'] == 'new_dashboard') {
            $limit = 10;
            $rowsCnt = mysql_num_rows(mysql_query($sql));
            $pagesCntForDashboard = ceil($rowsCnt/$limit);  
        }elseif(isset($filter['price_section_type']) ){
			if( isset($filter['deviceType']) && $filter['deviceType'] == 'ios')
				$limit = 8;
			elseif($resourceType=='web')
				$limit = 3000;
			else
				$limit = 11;
		}elseif(isset($cr_data))
		    $limit = RECOMMENDED_LIMIT;
		elseif($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		elseif($resourceType=='web' && (strtolower($source)=='commoditywise' || strtolower($source)=='regionwise'))
			$limit = 3000;
		elseif(isset($filter['download']) && $filter['download']=='y')
			$limit = 3000;
		/* elseif($source=='keyindex' || $source=='watchlist') 
			$limit = KEYPRICES_LIMIT;*/
		else 
			$limit = DEFAULT_PRICES_LIMIT;
			//$limit = DEFAULT_LIMIT;
		
		if(isset($filter['fromdate']) && $filter['fromdate'] != '') {
			//if its for customized case then dont apply any limit. send all data
		}elseif(!$chkSource){
			$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		}elseif(strtolower($source)!='mapview'){
			$sqlIds = $sql;
			$sqlIds .= " LIMIT " . (int)$offset . ", " . (int)$limit;
			
 			if(isset($filter['debug']) && $filter['debug'] == 1) {
				echo "sqlIds:" . $sqlIds . "<br />";
			}		
			
			$parenIDS='0';
			$parenIDSQry = qryToCommaSepString($sqlIds);
		//	if(isset($filter['debug']) && $filter['debug'] == 1) {
			//	echo "<br /> parenIDSQry:" . $sqlIds . "<br />";
		//	}
 			if($parenIDSQry=='')
				$parenIDSQry = -1;
			$CparenIDSQry = qryToCommaSepString("select relation_id from tbl_price_static where parentID in ($parenIDSQry)");
			if($parenIDSQry){
				if($CparenIDSQry)
					$parenIDSQry.=','.$CparenIDSQry;
				$addCond = " AND (m.`id` IN($parenIDSQry) OR n.parentID IN($parenIDSQry)) ";
				if( $s_ids == '' )
					$sql = str_replace(" and n.parentID=0", $addCond , $sql);
				else
					$sql = str_replace("m.`id` > 0", "m.`id` > 0 " . $addCond , $sql);
			}else{
				///echo 'NA';
			}
		}

		if(isset($filter['considerTableName']) && $filter['considerTableName'] != '') {
			$sql = str_replace("tbl_price_static", $filter['considerTableName'], $sql);
		}
		
		$query = mysql_query($sql);
		if(isset($filter['debug']) && $filter['debug'] == 1) {
			echo "count: " . mysql_num_rows($query);
			echo "<br /> sql:" . $sql . "<br />";
		}	
		$region='';$regionCnt = 0;
		$viewMore = array();
		$result = array();
		$prices = array();
		$assessments = [
			'D'	=>	'Daily',
			'W'	=>	'Weekly',
			'M'	=>	'Monthly',
			'BW'	=>	'Biweekly'
		];	
		
		$mapp = '';
        if(isset($filter['mapp_css']) && $filter['mapp_css'] != '') {
            /*if( $memid == 56350 )
                $mapp = file_get_contents("https://www.theitbooth.com/nw/storage/cssEnc/" . $filter['mapp_css'] . ".json");
            else    */
                $mapp = file_get_contents(siteUrl . "storage/cssEnc/" . $filter['mapp_css'] . ".json");
            $mapp = json_decode($mapp,true);
			
		}		
        if( $memid == 116707 ){		
            //echo "https://www.steelmint.com/nw/storage/cssEnc/" . $filter['mapp_css'] . ".json";
            //echo "<pre>";
           // print_r($mapp);
            //print_r($filter['mapp_css']);
        }
        

        $user = new User($memid, $appType);
        $user->isAccessible($resourceType, $section='Prices','','','',$filter["selected_market"]);
		while($row = mysql_fetch_assoc($query)){ 
            $pageType=$pageType_1;
            if($pageType_1=='post'){             
                $isAccessibleMkr =  $user->isAccessibleMarketWise($row['f_market']);
                if($isAccessibleMkr!=-1){
                    $pageType='pre';
                }
            }
			$flag=$row['flag']!=''?strtolower($row['flag']):'noflag';			
			$sectionHeading='';
			$subSectionHeading='';
			//print_r(session()->all());
			if(strtolower($source)=='commodity' || strtolower($source)=='commoditywise' || (isset($filter['tabFilter']) || $filter['tabFilter']=='home') || (isset($filter['price_section_type']) && $resourceType=='web')){
				/* $sectionHeading = $row['category'];
				$subSectionHeading = $row['sub_category']; */
				if($row['regionID'])
					$sectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='commodity' and ID=".$row['SubCommodityID']);
				if($row['regionID'])
					$subSectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['regionID']);
			}elseif(strtolower($source)=='region' || strtolower($source)=='regionwise' ){
				if($row['regionID'])
					$sectionHeading  = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['regionID']);
				if($row['SubCommodityID'])
					$subSectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='commodity' and ID=".$row['SubCommodityID']);
				/* if($row['parentRegionID'])
					$sectionHeading  = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['parentRegionID']);
				if($row['regionID'])
					$subSectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['SubCommodityID ']); */
			}
			
			$futureTblIds = array(3017,3018,3019);
			$futureTblIdsNew = array(3101,3100,3099,3098,3097,3096,3095,3094,3089,3088,3087,3086,3093,3092,3091,3090,3085,3084,3083,3082,3081,3080,3079,3075);
			if(in_array($row['id'],$futureTblIds)){
				$datePublishedIN = 'CST';
			}elseif(in_array($row['id'],$futureTblIdsNew)){
				$datePublishedIN = 'CST';
			}else{
				$datePublishedIN = 'IST';
			}
			
			array_push($futureTblIds, 1477);
			array_push($futureTblIds, 3021);
		/*	if( $memid == 116682 &&  $row['id'] == 1468 ){
			    echo "<br /> sh:" . $sectionHeading;
			    echo "<br /> ssh:" .  $subSectionHeading;
			}*/
			
			$result['itemID'] = intval($row['id']);
			$result["flagUrl"] = "https://www.steelmint.com/steeladmin/flags/".$flag.".png";
			$result["sectionHeading"] = utf8_decode($sectionHeading);
			$result["subSectionHeading"] = utf8_decode($subSectionHeading);
			//$result["title"]= $row['sticky_header_value'].' : '.$row['particular'];
			$result["title"]= $row['title'];
			$result["sticky_header_value"]= $row['sticky_header_value'];
			
			//$hrf = BASEURL."price/".url_title($row['title'].'-'.$row['id'],$separator = '-', $lowercase = true);
			$hrf = config('constants.siteUrl')."prices/detail/".url_title($row['title'].'-'.$row['id'].'-'.$row['f_cnf_fob'].'-'.$row['currency'],$separator = '-', $lowercase = true);
			$result["href"]=$hrf;
			$result["subTitle"]= utf8_decode($row['size_grade']);
			$result["compareTitle"]= utf8_decode($row['title']);
			$result["compareSubTitle"]= utf8_decode($row['size_grade']);
			///$result["datePublished"]= date('Y-m-d H:i:s', strtotime($row['date_time']));
			$result["datePublished"]= in_array($row['id'],$futureTblIds)?date('Y-m-d H:i:s', strtotime($row['date_time'])):date('Y-m-d H:i:s', strtotime($row['date_time_formatted']));
			$result["datePublishedIN"]= $datePublishedIN;
			$result["regionID"] = intval($row['regionID']);
			$result["regionName"] = is_null($row['regionName'])?'Others':$row['regionName'];
			$result["commodityID"] = intval($row['SubCommodityID']);
			$result["subSubCommodityID"] = intval($row['subSubCommodityID']);
			$result["commodityName"] = utf8_decode($row['commodityName']);
			$result["subCommodityName"] = utf8_decode($row['subCommodityName']);
			$result["showOnlyInSteelmint"] = utf8_decode($row['showOnlyInSteelmint']);
			//$result["assessment"]= $row['assessment'];
			$result["assessment"]= isset($assessments[$row['assessment']]) ? $assessments[$row['assessment']] : '';
			$f_cnf_fob= $row['f_cnf_fob'];
			$result["assessmentText"]=	isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment'];
			$result["isAddedToPortfolio"] = $row['portfolio']!=0?'y':'n';
			$result["isSetAlert"] = $row['isSetAlert']!=''?'y':'n';
			$result["isBookmarked"] = "n";
			$result["Location"] = is_null($row['location'])?'':$row['location'];
			/* list($lat,$long) = explode(',', $row['lat_long']);
			$result["latitude"] = (double)$lat;
			$result["longitude"] = (double)$long; */ // nashik
			
			$result["latitude"] = (double)$row['latitude'];
			$result["longitude"] = (double)$row['longitude'];
			
			$_currencyName = $row['currency'];
			
			$currencySymbolDefault = preg_replace('#[a-z0-9.]*#i', '',$row['price']);
			/* if($f_cnf_fob=='f'){
				$currencyConvertor = isset($currencyINRTO[$_currency])?$currencyINRTO[$_currency]:1;
				///$_currencyName='INR';
			}else{
				$currencyConvertor = isset($currencyUSDTO[$_currency])?$currencyUSDTO[$_currency]:1;	
				///$_currencyName='USD';				
			} */
			$currencyConvertor = 1;
			$dbCurrency = 0;
			if( $_currencyName == 'RMB' )
				$_fromcurrencyName = 'CNY';
			elseif( $_currencyName == 'YEN' )
				$_fromcurrencyName = 'JPY';
			else
			    $_fromcurrencyName = $_currencyName;
			if( $_currency == 'RMB' )
				$_tocurrency = 'CNY';
			elseif( $_currency == 'YEN' )
				$_tocurrency = 'JPY';
			else
			    $_tocurrency = $_currency;
			    
			if($_currency){
			    
			    if ($_fromcurrencyName == 'CEN' ){
			        //data enterd in cent is basis of (1 cent/lb = 22.48/MT)
			        //means, if we are tryign to convert from CENT to any other currency then we will multiple USD value by 22.48
			        $multiplyFactor = 22.48;
			        $_fromcurrencyName = 'USD';
			    } else {
			        $multiplyFactor = 1;
			    }
			    
				$sqlTC = "
				    select (conversion_rate * $multiplyFactor) as conversion_rate
					from tbl_currency_convertor
					where 1 and from_currency_code='$_fromcurrencyName' and to_currency_code='$_tocurrency'
					order by f_datetime desc
					limit 1
				";
        		 if(isset($filter['debug']) && $filter['debug'] == 2) {
                    echo $sqlTC . "<br />";
                } 	
				
				$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);
				if(mysql_num_rows($rsTC)>0){
					$rowTC = mysql_fetch_assoc($rsTC);
					$currencyConvertor = $rowTC['conversion_rate'];	
					$dbCurrency = 1;					
				}
			}
			
			///$currencySymbol = isset($symbolType[$_currency])?$symbolType[$_currency]:$currencySymbolDefault;	
			$currencySymbol = isset($symbolType[$_currency])?$symbolType[$_currency]:$symbolType[$_currencyName];	
			
			$_currencyName = $_currency!='' && $dbCurrency==1?$_currency:$_currencyName;
			
			/* if($row['SubCommodityID']==421 && $f_cnf_fob!='f'){
				//$_pref="&cent; ";$_suff="/lb";
				$_currencyName='CENT/LB';
			}elseif($row['SubCommodityID']==426 && $f_cnf_fob!='f'){
				//$_pref="USD ";$_suff="/dmtu";
				$_currencyName.='/DMTU';
			}else
				$_currencyName.='/MT'; */
			/* if($row['SubCommodityID']==421 && $f_cnf_fob!='f'){
				//$_pref="&cent; ";$_suff="/lb";
				$perUnit='/LB';
			}elseif($row['SubCommodityID']==426 && $f_cnf_fob!='f'){
				//$_pref="USD ";$_suff="/dmtu";
				$perUnit='/DMTU';
			}else
				$perUnit='/MT'; */
			if($resourceType=='web' &&  $currencySymbol!='')
				$currencySymbol=  str_replace(",",";&#x", $currencySymbol).';';
			$result["currency"] = 
						array(
						  "symbol" => !empty($currencySymbol)?$currencySymbol:"",//"₹"
						  "name" => !empty($_currencyName)?$_currencyName:""
						);
			/* $result["currency"] = 
						array(
						  "symbol" => "U+00A2",//"₹"
						  "name" => "&#x00a2;"
						); */	
						
			if($result['itemID']==5331 && strpos( trim(strip_tags($row['price'])), "-" ) !== false) {
				
				$result["price"]= $pageType=='pre'?'hidden': trim(strip_tags($row['price']));  
				$currencySymbolDefault='$';
			}else{
				$result["price"]= $pageType=='pre'?'hidden': trim(strip_tags($row['price']), 	$currencySymbolDefault);
			}
			
			$mprice = str_replace(",","",$result["price"]);
			$isDoubleVal = false;
			
			if($result["price"]!='' && $result["price"]!='NA' && $pageType=='post'){
				$result["price"] = str_replace(",","",$result["price"]);
				//if(is_double($result["price"])){
				if ( strpos( $result["price"], "." ) !== false ){
					if(intval($result["price"])<2)
					$result["price"] = number_format(str_replace(",","",$result["price"])*$currencyConvertor,4);
					else
					$result["price"] = number_format(str_replace(",","",$result["price"])*$currencyConvertor,2);
					
					$isDoubleVal = true;
				}else{
					$result["price"] = number_format($result["price"]*$currencyConvertor);
				}
			}
			//$result["price"] = (string)$result["price"].$perUnit;
			$result["price"] = (string)$result["price"];
			$result["priceType"] = utf8_decode($f_cnf_fob);
			if($f_cnf_fob=='f')
				$tradeType = 'Domestic';
			elseif($f_cnf_fob=='cnf')
				$tradeType = 'Import';
			elseif($f_cnf_fob=='fob')
				$tradeType = 'Export';
			elseif(in_array($row['id'],$futureTblIds))
				$tradeType = 'Future';
			
			$show_intraday='';
			if(( intval($row['SubCommodityID'])==443 ||  intval($row['SubCommodityID'])==439 ||  intval($row['subSubCommodityID'])==471 ) &&  utf8_decode($f_cnf_fob)=='f')
			{
				$show_intraday='Y';	
			}
			$result["showIntraDay"] = $show_intraday;
			$cbc_ass = array(3051,3050,3049,3048,3047,3046,3045,3044,3043,3042,3041,3040,3039,3038,3037,3036,3035,3034,3033,3032,3031,3030,3029,3028,3027,3026);
			if(in_array($result["itemID"],$cbc_ass))
				$result["dataSource"] = 'CBC';
			else
                $result["dataSource"] = 'BigMint';
				//$result["dataSource"] = $row['commodityID']==401?'CoalMint':'SteelMint';
			$result["tradeType"] = utf8_decode($tradeType);
			$result["tradeType3Chars"] = strtoupper(substr(utf8_decode($tradeType), 0, 3));
			///$result["delayed"] = trim(preg_replace("/\r|\n/", "", $row['remark']));
			$result["delayed"] = '';//strpos( strtolower($row['remark']), "early" ) === false?trim(preg_replace("/\r|\n/", "", $row['remark'])):"";
			$result["early"] = '';//strpos( strtolower($row['remark']), "early" ) !== false?trim(preg_replace("/\r|\n/", "", $row['remark'])):"";
			if($result["assessment_comments"]!='' && $result["assessment_comments"]=='Delayed')
				$result["delayed"] = $row['remark'];
			elseif($result["assessment_comments"]!='' && $result["assessment_comments"]=='Early')
				$result["delayed"] = $row['remark'];
			
			$result["countryCode"] = $row['regionID']>0?qryToCommaSepString("SELECT country_code_3_chars FROM `tbl_country` where id=".$row['regionID']):'NA'; 
			
			$change = str_replace("&nbsp;", "", strip_tags(trim(preg_replace("/\r|\n/", "", $row['change']))));
			$change = str_replace(',', '', $change);
			$strtrarr = array(" " => "");
			$_changeValue = strtr($change, $strtrarr);
			if($_changeValue!='NA' && $_changeValue!='-' && $pageType=='post'){
				//$changeInPricePercentage = round((($_changeValue/$mprice)*100), 1);
				//$_changeValue = $_changeValue*$currencyConvertor;
				/* if(is_double($_changeValue)){
					$changeInPricePercentage = number_format((($_changeValue/$mprice)*100), 1);
				}else{
					$changeInPricePercentage = number_format((($_changeValue/$mprice)*100));
				} */
				

				//$changeInPricePercentage = ($_changeValue/$mprice)*100;
				/*
					logic changed on 8-sep-2021
					
				*/
				$changeInPricePercentage = ($_changeValue/($mprice-($_changeValue)))*100;
				if( $changeInPricePercentage >= 1 ){
					$changeInPricePercentage = round($changeInPricePercentage, 1);
				} else {
					$changeInPricePercentage = round($changeInPricePercentage, 1);
				}
				$_changeValue = round($_changeValue*$currencyConvertor,2);
				
				$result["heatMapColor"] = getHeatMapColor($changeInPricePercentage);
			}else{
				$changeInPricePercentage = '-';
				$result["heatMapColor"] = [];
			}
			
			if( $changeInPricePercentage == '-' )
				$changeInPricePercentage = '';	
			
			//$result["isChangePositive"] = $pageType=='pre'?'hidden': ($_changeValue>0?"y":"n");
			$result["isChangePositive"] = ($_changeValue==0|| $_changeValue=='NA')? '': ($_changeValue>0?"y":"n");
			$result["changeInPrice"]= $pageType=='pre'?'hidden': (string)$_changeValue;
			$result["changeInPricePercentage"]= $pageType=='pre'?'hidden':(string)$changeInPricePercentage;
			$result["mnthly_avg_dtls"]= $row['mnthly_avg_dtls'];
		
			
			/* $change = str_replace("&nbsp;", "", strip_tags(trim(preg_replace("/\r|\n/", "", $row['change']))));
			//$strtrarr = array(" " => "", "-" => "", "+" => "");
			$strtrarr = array(" " => "");
			$_changeValue = strtr($change, $strtrarr);
			if($_changeValue!='NA' && $_changeValue!='-'){
				$changeInPricePercentage = round((($_changeValue/$mprice)*100), 2);
			}else
				$changeInPricePercentage = '-';
			
			$result["isChangePositive"] = $pageType=='pre'?'hidden': $_changeValue>0?"y":"n";
			$result["changeInPrice"]= $pageType=='pre'?'hidden': $change;
			///$result["changeInPricePercentage"]= $pageType=='pre'?'hidden':$row['changeInPricePercentage'];
			
			$result["changeInPricePercentage"]= $pageType=='pre'?'hidden':$changeInPricePercentage; */
			
			
			$_1w = trim(strip_tags($row['1W']), $currencySymbolDefault);
			$_1m = trim(strip_tags($row['1M']), $currencySymbolDefault);
			$_3m = trim(strip_tags($row['3M']), $currencySymbolDefault);
			$min_price = trim(strip_tags($row['min_price']), $currencySymbolDefault);
			$max_price = trim(strip_tags($row['max_price']), $currencySymbolDefault);
			
			if($_1w!='' && $_1w!='NA' && $pageType=='post')
				$_1w = $isDoubleVal? number_format(str_replace(",","",$_1w)*$currencyConvertor, 1):number_format(str_replace(",","",$_1w)*$currencyConvertor);
			if($_1m!='' && $_1m!='NA' && $pageType=='post')
				$_1m = $isDoubleVal? number_format(str_replace(",","",$_1m)*$currencyConvertor, 1):number_format(str_replace(",","",$_1m)*$currencyConvertor);
			if($_3m!='' && $_3m!='NA' && $pageType=='post')
				$_3m = $isDoubleVal? number_format(str_replace(",","",$_3m)*$currencyConvertor, 1):number_format(str_replace(",","",$_3m)*$currencyConvertor);
			if($min_price!='' && $min_price!='NA' && $pageType=='post')
				$min_price = $isDoubleVal? number_format(str_replace(",","",$min_price)*$currencyConvertor, 1):number_format(str_replace(",","",$min_price)*$currencyConvertor);
			if($max_price!='' && $max_price!='NA' && $pageType=='post')
				$max_price = $isDoubleVal? number_format(str_replace(",","",$max_price)*$currencyConvertor, 1):number_format(str_replace(",","",$max_price)*$currencyConvertor);
			
			$result["1W"] = $pageType=='pre'?'hidden':(string)$_1w;
			$result["1M"] = $pageType=='pre'?'hidden':(string)$_1m;
			$result["3M"] = $pageType=='pre'?'hidden':(string)$_3m;
			if( isset($filter['deviceType']) && $filter['deviceType'] == 'ios'){
			//if( 0){
				$details = array(
					array("key" => 'Min Price'	, "value"				=>					$pageType=='pre'?'hidden':(string)$min_price),
					array("key" => 'Max Price', "value"					=>						$pageType=='pre'?'hidden':(string)$max_price),
					array("key" => 'Currency'	, "value"				=>			utf8_decode($row['currency'])),
					array("key" => 'Physical Composition'	, "value"	=>			utf8_decode($row['f_size'])),
					array("key" => 'Chemical Composition', "value"		=>			utf8_decode($row['chemical_composition'])),
					array("key" => 'Delivery Terms', "value"			=>			utf8_decode($row['delivery_terms'])),
					array("key" => 'Payment Terms', "value"				=>			utf8_decode($row['payment'])),
					array("key" => 'Quantity', "value"					=>			utf8_decode($row['quantity'])),
					array("key" => 'Delivery Period', "value"			=>			utf8_decode($row['delivery_period'])),
					array("key" => 'Taxes'	, "value"					=>			utf8_decode($row['taxes'])),
					array("key" => 'Assessment'	, "value"	=>				isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment']),
					array("key" => 'Publication Day/Time'	, "value"	=>			utf8_decode($row['publication_day_time'])),
					array("key" => 'Remarks', "value"	=>						utf8_decode($row['remarks'])),
					array("key" => 'Sentiments', "value"	=>				$row['sentiments'] ? $row['sentiments'] : 'NA'),
					array("key" => 'Methodology', "value"	=>				$pageType=='pre'?'hidden':$row['f_methodology']),
								
				);				
			}
			else if( isset($filter['API_Key']) && $filter['API_Key'] == 'vByzPZgA5gdMP') {
				$details = array(
					'itemID'                => intval($row['id']),
					'Min Price'				=>	$pageType=='pre'?'hidden':(string)$min_price,
					'Max Price'				=>	$pageType=='pre'?'hidden':(string)$max_price,
					'Currency'				=>	utf8_decode($row['currency']),
					'Physical Composition'	=>	utf8_decode($row['f_size']),
					'Chemical Composition'	=>	utf8_decode($row['chemical_composition']),
					'Delivery Terms'		=>	utf8_decode($row['delivery_terms']),
					'Payment Terms'			=>	utf8_decode($row['payment']),
					'Quantity'				=>	utf8_decode($row['quantity']),
					'Delivery Period'		=>	utf8_decode($row['delivery_period']),
					'Taxes'					=>	utf8_decode($row['taxes']),
					'Assessment'			=>	isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment'],
					'Publication Day/Time'	=>	utf8_decode($row['publication_day_time']),
					'Remarks'				=>	utf8_decode($row['remarks']),
					'Sentiments'			=>	$row['sentiments'] ? $row['sentiments'] : 'NA',
					'Methodology'			=>	$pageType=='pre'?'hidden':$row['f_methodology']
					
				);		
			}
			else {
				$details = array(
					'Min Price'				=>	$pageType=='pre'?'hidden':(string)$min_price,
					'Max Price'				=>	$pageType=='pre'?'hidden':(string)$max_price,
					'Currency'				=>	utf8_decode($row['currency']),
					'Physical Composition'	=>	utf8_decode($row['f_size']),
					'Chemical Composition'	=>	utf8_decode($row['chemical_composition']),
					'Delivery Terms'		=>	utf8_decode($row['delivery_terms']),
					'Payment Terms'			=>	utf8_decode($row['payment']),
					'Quantity'				=>	utf8_decode($row['quantity']),
					'Unit Of Measurement'		=>	utf8_decode($row['unit_of_measurement']),
					'Delivery Period'		=>	utf8_decode($row['delivery_period']),
					'Taxes'					=>	utf8_decode($row['taxes']),
					'Assessment'			=>	isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment'],
					'Publication Day/Time'	=>	utf8_decode($row['publication_day_time']),
					'Remarks'				=>	utf8_decode($row['remarks']),					
					'Sentiments'			=>	$row['sentiments'] ? $row['sentiments'] : 'NA',
					'Methodology'			=>	$pageType=='pre'?'hidden':$row['f_methodology']
					
				);				
			}
			
			if($resourceType=='app'){
				$details = array_filter($details);
			}
			/* if( isset($filter['deviceType']) && $filter['deviceType'] == 'ios'){	
				$details1 =array();
				foreach($details as $k=>$val){
					$details1[] =  array("key" => $k, "value"	=>	$val);
				}
				$result["details"] = $details1;
			}else */
				$result["details"] = $details;
			//$result["methodologyUrl"]= $pageType=='pre'?'hidden':BASEURL."price_methodology.php?rid=".$result['itemID'];
			$result["methodologyUrl"]= BASEURL."app_webview_pages/price_methodology.php?rid=".$result['itemID'];
			/* $result["heatmapColor"] = "#FF0000"; */
			///$result["costIndex"]= $pageType=='pre'?'hidden':"https://www.w3schools.com/html/nd/default.asp";
			//$result["rationale"]= $pageType=='pre'?$memid?'':'hidden':BASEURL."rationale.php?rid=".$result['itemID'];
			$rationale = '';
			if( $row["rationale"] != '' )
				$rationale = BASEURL."rationale.php?rid=".$row['id'];

			if(isset($filter['debug']) && $filter['debug'] == 1) {
				
				if( $row["id"] == 1401 ){
					echo "pt:" . $pageType;
					echo $rationale;
				}	
			}
			
			if( $pageType=='pre' ){
				$rationale = 'hidden';
			} else {
				if( $rationale == '' )
					$rationale = 'hidden';
			}
			
			$result["rationale"]=$rationale; 
			//$result["rationale"]= $pageType=='pre'?$memid?$rationale:'hidden':'';//send blank for paid+logged users. this will make sure the rationale tab is not shown in the app
			
			$result["parentID"]= $row['parentID'];
			$result["viewMoreText"]= utf8_decode($row['view_more_text']);
			$result["publicationDayTime"]= utf8_decode($row['publicationDayTime']);
			if(isset($row['metaDescription'])){
				$result['metaDescription'] = utf8_decode($row['metaDescription']);
				$result['metaKeyword'] = utf8_decode($row['metaKeyword']);
			}
			//if($source!='alerts' && $row['parentID']>0 && isset($mainEle1[$row['parentID']])){

//START: following code added by tarun on 2021-04-02 to encode price values for anmol id
			//if( $memid == 116707 ){
			if(isset($filter['mapp_css']) && $filter['mapp_css'] != ''){    
                //echo "<br />before:" . $result["price"];				
				$result["price"] = \ApiQuery::encodeVals($result["price"], $mapp);
				//echo "<br />after:" . $result["price"];				
				//$result["changeInPrice"] = \ApiQuery::encodeVals($result["changeInPrice"], $mapp);
				//$result["changeInPricePercentage"] = \ApiQuery::encodeVals($result["changeInPricePercentage"], $mapp);
				$result["1W"] = \ApiQuery::encodeVals($result["1W"], $mapp);
				$result["1M"] = \ApiQuery::encodeVals($result["1M"], $mapp);
				$result["3M"] = \ApiQuery::encodeVals($result["3M"], $mapp);
			}
//END: following code added by tarun on 2021-04-02 to encode price values for anmol id

			
			if(isset($filter['prices_assessments_to_show'])){
				$prices_assessments_to_show_cnt++;
				$f_cnf_fob = $f_cnf_fob.'-'.$prices_assessments_to_show_cnt;
			}
				
			if($chkSource==true && $row['parentID']>0){
				//echo $row['parentID'].'--'.$row['id'].'<br>';
				if(!isset($mainEle[$row['parentID'].$f_cnf_fob]))
					$mainEle[$row['id'].$f_cnf_fob] = $result;				
				else
					$childEle[$row['parentID'].$f_cnf_fob][$row['id'].$f_cnf_fob] = $result;				
			}else{
				//$mainEle[] = $result;
				$mainEle[$row['id'].$f_cnf_fob] = $result;
				//$mainEle1[$row['id']] = $row['parentID'];
			} 
		
			if($pageType=='pre'){
				$content = 'hidden';
			}
		}
		
		if(isset($filter['debug']) && $filter['debug'] == 1) {
		echo "<pre>";
		print_r($mainEle);
		}
		
		$childArray = array_diff($parentEle1, array_keys($parentEle));	
		foreach($mainEle as $itemID=>$child):
			$childT = $child;
			foreach($childEle[$itemID] as $chilID=>$childArr){
				$child['viewMore'][$chilID]=$childArr;
				
				foreach($childEle[$chilID] as $subChilID=>$subChildArr){
					$child['viewMore'][$chilID]['viewMore'][$subChilID]=$subChildArr;
						
						foreach($childEle[$subChilID] as $subSubChilID=>$subSubChildArr){
							$child['viewMore'][$chilID]['viewMore'][$subChilID]['viewMore'][$subSubChilID]=$subSubChildArr;//4th levels
							$subChildArr['viewMore'][] = $subSubChildArr;
						}
					$childArr['viewMore'][] = $subChildArr;					
				}
				
				$childT['viewMore'][]=$childArr;
			}
			$prices[] = $child;
			$pricesT[] = $childT;
		endforeach;

        /*$finres = array();
        $finres["dataValue"] = $pricesT;
        $finres["cntValue"] = $rowsCnt;*/

        if(isset($filter['renderAt']) && $filter['renderAt'] == 'new_dashboard') {
            $finres = array();
            $finres["dataValue"] = $pricesT;
            $finres["cntValue"] = $pagesCntForDashboard;
            
            return $finres;
        } else {
            return $pricesT;
        }

		//return $pricesT;
    }

	function encodeVals($val, $arrEncodedNos){
	    //return $val;

	    
	    $val = trim($val);
	    if( $val == "NA" || $val == "hidden" ||  $val == "")
	        return $val;
	    $val = strval($val);

		$ex = str_split($val);
		
		$retValue = '';
		for($i = 0; $i < count($ex); $i++){
			$retValue .= '<span id="' . $arrEncodedNos[$ex[$i]] . '"></span>'; 
		}
		
		return $retValue;
	}
	
	function createTreeView($array, $currentParent, $currLevel = 0, $prevLevel = -1) {
		
		$res = array();
		foreach ($array as $categoryId => $category) {

		if ($currentParent == $category['parentID']) {                       
			if ($currLevel > $prevLevel) echo " <ol class='tree'> "; 

			if ($currLevel == $prevLevel) echo " </li> ";

			echo '<li> <label for="subfolder2">'.$category['itemID'].'-'.$category['parentID'].'</label> ';

			if ($currLevel > $prevLevel) { $prevLevel = $currLevel; }

			$currLevel++; 

			\ApiQuery::createTreeView ($array, $categoryId, $currLevel, $prevLevel);

			$currLevel--;               
			}   

		}

		if ($currLevel == $prevLevel) echo " </li>  </ol> ";
	}
	
	public static function getPricesCompareSavedRows($resourceType='app', $memid=0, $itemID=0, $limit=0, $offset=0){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		//$sqlTC = "select * from tbl_compare where memid=$memid and status=1"; 
		$sqlTC = "select c.*
					, rcm1.itemName as commodityID1Name, rcm2.itemName as commodityID2Name 
					,ps1.title as title1,ps2.title as title2
					,ps1.relation_id, ps2.relation_id
					from tbl_compare as c
					left join tbl_region_commodity_master as rcm1
					ON rcm1.ID=c.commodityID1
					left join tbl_region_commodity_master as rcm2
					ON rcm2.ID=c.commodityID2

					left join tbl_price_static as ps1
					ON ps1.relation_id=c.relationID1 AND ps1.f_cnf_fob=c.tradeType1
					left join tbl_price_static as ps2
					ON ps2.relation_id=c.relationID2 AND ps2.f_cnf_fob=c.tradeType2

					where memid=$memid and status=1  
					"; 
		if($itemID)
			$sqlTC .= " AND id=$itemID";
		if($resourceType)
			$sqlTC .= " AND resourceType='$resourceType'";
			$sqlTC .= " order by id desc";
		if($limit){
			$limit = DEFAULT_LIMIT;
			$sqlTC .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		}
		
		$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC); 
		$result = array();
		
		while($row = mysql_fetch_assoc($rsTC)){
			$temp = array();
			$row1['item1'] = array(
								
							);
			$temp['itemID'] = intval($row['id']);
			$temp['compareName'] = $row['compareName'];
			$temp['fromDate'] = $row['fromDate'];
			$temp['toDate'] = $row['toDate'];
			$temp['assessmentType'] = $row['assessmentType'];
			$temp['screenImage'] = $row['screenImage']!=''?BASEURL."api/public/uploads/compare/".$row['screenImage']:"";
			//$temp['toDate'] = $row['toDate'];
			$t1 = $row['dataType1']=='price'?$row['commodityID1Name']:$row['commodityID1'];
			$t2 = $row['dataType2']=='price'?$row['commodityID2Name']:$row['commodityID2'];
			$temp['item1'] = array(
								"dataType"=>ucwords(strtolower($row['dataType1'])),
								"tradeType"=>$row['tradeType1'],
								"commodityID"=>$row['dataType1']=='price'?(int)$row['commodityID1']:$row['commodityID1'],
								///"commodityName"=>$row['commodityID1Name'],
								"regionID"=>$row['dataType1']=='price'?(int)$row['regionID1']:$row['regionID1'],
								"relationID"=>(int)$row['relationID1'],
								"relationName"=>$row['commodityID1Name'].' | '.$row['2ndLevel1Value'],
								"columnNameOfRegion"=>$row['columnNameOfRegion1'],
								"columnNameOfCommodity"=>$row['columnNameOfCommodity1'],
								"childHeaderName"=>$row['2ndLevel1'],
								"childHeaderValue"=>$row['2ndLevel1Value'],
								"childHeaderColumn"=>$row['2ndLevel1headerColumn']
								//"tradeType"=>$row['tradeType1'],
							);
			$temp['item2'] = array(
								"dataType"=>ucwords(strtolower($row['dataType2'])),
								"tradeType"=>$row['tradeType2'],
								"commodityID"=>$row['dataType2']=='price'?(int)$row['commodityID2']:$row['commodityID2'],
								//"commodityName"=>$row['commodityID2Name'],
								"regionID"=>$row['dataType2']=='price'?(int)$row['regionID2']:$row['regionID2'],
								"relationID"=>(int)$row['relationID2'],
								"relationName"=>$row['commodityID2Name'].' | '.$row['2ndLevel2Value'], 
								"columnNameOfRegion"=>$row['columnNameOfRegion2'],
								"columnNameOfCommodity"=>$row['columnNameOfCommodity2'],
								"childHeaderName"=>$row['2ndLevel2'],
								"childHeaderValue"=>$row['2ndLevel2Value'],
								"childHeaderColumn"=>$row['2ndLevel2headerColumn']
								/*"2ndLevel"=>$row['2ndLevel2'], 
								"2ndLevelValue"=>$row['2ndLevel2Value'],*/
								//"tradeType"=>$row['tradeType2'],
							);
			$result[]=$temp;
		}
		
		if($type=='default'){
			//json file $result;
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $result;
	}
	
	public static function getPackagesRows($memid=0, $packageID=array(), $section='steelmint', $status='Active', $resourceType='app', $activePackegesIDs=array(), $appType='SM', $currencyName='INR',$deviceType='', $renderAt=''){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$result = array();
		$whrCond = " and showInWEB_APP ='Y' ";		
		if(count($activePackegesIDs)>0){
			///
			//$whrCond = " AND ";
		}		
				
		if($currencyName!=''){
            $whrCond .= " AND currency_code='$currencyName' ";
        }
		
		if(!empty($packageID)){
			$whrCond .= " AND `id` IN (" . implode(",", $packageID) .")";
		}
		if($resourceType=='app'){
    		if(strtolower($deviceType)=='ios'){
                $whrCond .= " AND `packageDetails` like '%_ios%' ";
            }else{
                $whrCond .= " AND `packageDetails` not like '%_ios%' ";
            }
		}
		/*if( $appType == 'CM' )
		    $whrCond .= " and `section` = 'coalmint' ";
		elseif( $appType == 'SM' )
		    $whrCond .= " and `section` = 'steelmint' "; */
		if($renderAt=='packageSlider')
			$whrCond .= " AND (`period_name` =12 or packageName ='Free Trial') ";
		$grp_part='';
		if($renderAt!='packageSlider')
            $grp_part = " group by group_id ";
        $sqlTC = "select * from tbl_packages
                where  section = '$section'
                and platform = '$resourceType'
                $whrCond
                $grp_part
                order by group_id desc, sub_group_id, package_order, currency_code
            ";
		$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC); 	
		
		while($row = mysql_fetch_assoc($rsTC)){              
			if($renderAt=='packageSlider'){
				
				$result[] = array("groupID" => $row['group_id'],
					"packageName" => $row['packageName'],
					"code" => $row['currency_code'] ,
					"amountPerMonth" => $row['amountPerMonth'],
					"packageID"  => $row['id'],
					'recommendation' => $row['recommendedFor']
				);
				
				
			}else{
                $sqlTC_1 = "select id from tbl_packages
                where  section = '$section'
                and platform = '$resourceType'
                and group_id='".$row['group_id']."'
                $whrCond
                order by period_name desc limit 1";
                $packageID_new = qryToCommaSepString($sqlTC_1);
			
				$groups[$row['group_id']] = array(
					'tabType' =>$row['tabType'],
					'groupID' =>$row['group_id'],
					'packageName' =>$row['packageName'],
					'isActivePackage' => in_array($row['id'], array_keys($activePackegesIDs))?'y':'n',
					'whatYouGet' => explode(",",$row['whatYouGet']),
					'recommendation' => $row['recommendedFor'],
					"packageID"  => $packageID_new,
					"market"=> array(
                            array("key"=>"ferrous", "label"=>"Ferrous Metals"),
                            array("key"=>"non-ferrous", "label"=>"Non Ferrous"),
                            array("key"=>"coal", "label"=>"Coal & Energy"),
                            array("key"=>"scrap-recycling", "label"=>"Scrap Recycling")
                        )
					
				);
				//Commented as per new api
				/*$periodName[$row['group_id']][$row['period_name']] = array(
					'periodName'=>(int)$row['period_name'],
					//'periodType'=>"Monthly",
					'periodType'=>$row['unit_of_tenure'],
					'isPeriodDisabled' => $row['package_order']<max($activePackegesIDs) ?'n':'n',
				);
				$licensesCount[$row['group_id']][$row['period_name']][$row['licenses_cnt']] = array(
					"count"=>$row['licenses_cnt'],
					'isLicenseDisabled' => $row['package_order']<max($activePackegesIDs)?'n':'n',
				);
				
				$currencyCode[$row['group_id']][$row['period_name']][$row['licenses_cnt']]['currencyCode'] = array(
												"code"=>$row['currency_code'] ,
												'billedText' => $row['billed_text'],
												'amountPerMonth' => $row['amountPerMonth'],
												'totalAmountWoGST' => $row['totalAmount_Wo_GST'],
												'totalAmountWithGST' => $row['totalAmount_With_GST'],
												'packageID' => $row['id'],											
												'currencySymbol' => $row['currency_symbol'],
												'scratchValue' => $row['scratch_value'],
												'actualPrice' => $row['actual_price'],
												'discountPercentage' => $row['discount_percentage'],
												'discountValue' => $row['discount_value'],
												'gstPercentage' => $row['gst_Rate'],
												'gstValue' => $row['gst_Amt'],											
												'IsDefault' => $row['IsDefault']											
											);
				*/
				
				///$result[] = $temp;
			}
		}
		
		if($renderAt=='packageSlider'){return $result;}
		/* foreach($groups as $group_id=>$group):
			$temp = $group;
			foreach($periodName[$group_id] as $period_name=>$period):
				$temp['periodName'] = $period;
				foreach($licensesCount[$group_id][$period_name]  as $licenses_cnt=>$licenses):
					$temp['periodName']["licensesCount"] = $licenses;
					foreach($currencyCode[$group_id][$period_name][$licenses_cnt]  as $licenses):
						$temp['periodName']["licensesCount"]['currencyCode'] = $licenses;
					endforeach;
				endforeach;
			endforeach;
			$result[] = $temp;
		endforeach; */
		foreach($groups as $group_id=>$groupArr){
			$temp = $groupArr;
			unset($temp['tabType']);
			//Commented as per new api
			/*$period = array();
			foreach($periodName[$group_id] as $period_name=>$periodArr){
				$period[$period_name] = $periodArr;
				$licenses = array();
				foreach($licensesCount[$group_id][$period_name] as $licenses_cnt=>$licensesArr){
					$licenses[$licenses_cnt] = $licensesArr;
					
					$licenses[$licenses_cnt]['currencyCode'] = $currencyCode[$group_id][$period_name][$licenses_cnt]['currencyCode'];
					
				}
				$period[$period_name]['licensesCount'] = array_values($licenses);
			}*/
			//$temp['periodName'] = array_values($period);
			$result[$groupArr['tabType']][] = $temp;
		}
		
		if($type=='default'){
			//json file $result;
		} 
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $result;
	}
	
	function sendRequestMailToRM($intrestedIN="Product Wise", $memid='', $rmId=''){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		if($memid){
			if($intrestedIN=='regMail'){
				$sub_txt = "SteelMint : New user registration ";
				$msg = "Dear All, ";
				
				$msg.= " <br><br>New Registration Details  : <a href='https://www.steelmint.com/steeladmin/operations/tem_screenshot/html/index_new.php?id=".$memid."' target='_new'>".$memid. "</a>";
				
				/*$qry = "
						select 
							CASE 
								when d.billing_name = '' then d.name
								else d.billing_name
							END as billing_name, job_title, company,
							short_comptype as company_type,
							CASE 
								when send_email_to = 'R' then email
								else addtnl_email
							END as email, 
							CASE 
								when send_sms_to = 'R' then phoneno
								else alternate_mob_no
							END as phoneno,
							sc.state_name as state,
							c.country
						from tbl_members as d
						left join tbl_companytype as ct ON ct.id = d.companytype
						left join tbl_state_city sc
						ON d.country=sc.country_id
						AND d.state=sc.state_id
						left join tbl_country c
						ON d.country=c.id
						where d.id =$memid
					";
				$msg.='<table border="2">';
				$rsTC = mysql_query($qry)or die(mysql_error().$qry); 	
				while($row=mysql_fetch_assoc($rsTC)){
					foreach($row as $key=>$val){
						$key=ucwords(str_replace('_',' ', strtolower($key)));
						$msg.='<tr><td>'.$key.'</td><td>'.$val.'</td></tr>';
					}
				}				
				$msg.='</table>';
				*/
				$rmEmail='sumit@steelmint.com,dhruv@steelmint.com,kshitij@steelmintgroup.com';
				include_once "/home/steelmin/public_html/mf.php"; 
				$res = sendSMMail($msg, $rmEmail, "", $sub_txt, $invFileName='', $rmEmail="info@steelmint.com", $rmName="Registraion", $rmEmail="info@steelmint.com");
				
			}else{
				if($rmId){
					$qry = "
						select rel_manager, RM_name, Position, RM_phoneno, RM_email, RM_telephoneno
						from tbl_rel_manager
						where id =$rmId
					";
				}else{
					$qry = "
						select rel_manager, RM_name, Position, RM_phoneno, RM_email, RM_telephoneno
						from tbl_rel_manager
						where id =
						(
							select subrm
							from tbl_reg_logs
							where memid=$memid
							and f_product in ('W','S','MA','MA_PO','E','SM-R','SM-A')
							order by id desc limit 1
						)
					";
				}
				
				$rsTC = mysql_query($qry)or die(mysql_error().$qry); 	
				$rm_signature='';
				include_once "/home/steelmin/public_html/mf.php"; 
				while($row=mysql_fetch_array($rsTC)){	
				
					$rm_signature = rmSignatureFormate($row, $dom_exim='Dom');
					$rmEmail = $row['RM_email'];	
					//$rmEmail = 'mohan@theitbooth.com';	
					//$rmName = $row['RM_name'];	
					$rmName = $row['rel_manager'];	
					
					$sub_txt = "This user shows, his interest in ".$intrestedIN." Package";
					$msg = "Dear ". $rmName;
					
					$msg.= " Memid : <a href='https://www.steelmint.com/steeladmin/operations/tem_screenshot/html/index_new.php?id=".$memid."' target='_new'>".$memid. "</a>, shows there interest in ".$intrestedIN." Package.";
					
				
					$res = sendSMMail($msg, $rmEmail, "", $sub_txt, $invFileName='', $rmEmail="info@steelmint.com", $rmName="Registraion", $rmEmail="info@steelmint.com");
					
				}
				if(strtolower($intrestedIN)=='free trial'){
					//include_once "/home/steelmin/public_html/inc/desconfig.php";
					return "Thank You! Your Free Trial request has been taken. We will get in touch with you shortly. For any assistance reach us on info@steelmint.com or call +91 97700 56666";		
					//return "Thankyou! Your free trial is activated for the duration ".date('d-m-Y')." to ".date('d-m-Y', strtotime('+7 days')).". For any assistance reach us on info@steelmint.com or call +91 97700 56666";			//return $rm_signature;
				}else{
					//include_once "/home/steelmin/public_html/inc/desconfig.php";
					return "Thank you for your interest our Relationship Manager will get in touch with you soon";
				}			//return $rm_signature;
			}
		}else{
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return '';
		}
	}
	
	public static function emailSampleReport($email, $itemID){
		//include_once "/home/steelmin/public_html/inc/config1.php";
	    $a = mysql_query("select file 
	    from tbl_steelreports_category    
	    where id = $itemID");
	    
	    $b = mysql_fetch_array($a);
	    $sampleFile = $b["file"];
	    
	    $msg = "Dear Patron <br/ ><br/ > Please find attached the sample file.";
	    $sub_txt = "SteelMint: sample report";
	    include_once "/home/steelmin/public_html/mf.php"; 
		$res = sendSMMail($msg, $email, "", $sub_txt, $sampleFile, $rmEmail="info@steelmint.com", $rmName="SteelMint", $rmEmail="info@steelmint.com");
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
	}
	
	public static function reportsCategoryCount($filter=array()){
        //include_once "/home/steelmin/public_html/inc/config1.php";
//		$sql = "select f_special_regular, group_concat(id) as 'ids'        from tbl_steelreports_category as n";
		$sql = "select f_special_regular, count(id) as 'cnt'  from tbl_steelreports_category as n";
		
		$sql .= " WHERE n.`id` > 0  ";//and n.id!='25' and  n.id!='20'
		
		if($resourceType=='app'){
			$sql .= " AND n.`f_special_regular`='r'";
			$sql .= " AND (showInMobApp=1)";
		}
		if(isset($filter['reportID']) && !empty($filter['reportID'])) {// for a particular category
			if(is_array($filter['reportID']))
				$sql .= " AND n.`id` IN (" . implode(',',$filter['reportID']) .")";
			else
				$sql .= " AND n.`id` = " . (int)$filter['reportID'];
		}
		
		if(isset($filter['type']) && !empty($filter['type'])) {
			$f_special_regular='0';
			if ($filter['type'] == "regular") {
				$f_special_regular = "r";
			} elseif($filter['type'] == "special") {
				$f_special_regular = "s";
			} elseif($filter['type'] == "knowledge center" || $filter['type'] == "knowledge") {
				$f_special_regular = "k";
			}
			
			$sql .= " AND n.`f_special_regular` = '$f_special_regular'";
		}
		
		if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
			
			$sql .= " AND (";
			foreach($filter['commodityID'] as $k=>$commodityID){
				if( $k> 0 )
					$sql .= " OR ";
				$sql .= " FIND_IN_SET({$commodityID},`commodityID`) > 0 ";
			}
			$sql .= " ) ";
		}
		
		if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {	
			
			$sql .= " AND (";
			foreach($filter['regionID'] as $k=>$regionID){
				if( $k> 0 )
					$sql .= " OR ";
				$sql .= " FIND_IN_SET({$regionID},`regionID`) > 0 ";
			}
			$sql .= " ) ";
		}
		
		if( isset($filter['app_type']) && $filter['app_type'] == 'CM'){
			$sql .= "";//for coalmint its check commodity id 401
		}else{
			$sql .= " AND website like '%steelmint.com%'";
		}
		
		 $sql.=" group by f_special_regular ";
		/* $a = mysql_query("select f_special_regular, group_concat(id) as 'ids'
        from tbl_steelreports_category 	 
        group by f_special_regular"); */
        $a = mysql_query($sql);
        
        $arrCnt = array();
        
        while($b = mysql_fetch_array($a)){
            $rptType = $b["f_special_regular"];    
            $cnt = $b["cnt"];

            if($rptType == 'r')
                $arrCnt['Regular'] = (int)$cnt;            
            if($rptType == 's')
                $arrCnt['Special'] = (int)$cnt;            
            if($rptType == 'k')
                $arrCnt['Knowledge'] = (int)$cnt;

            
           /* $c = mysql_query("select count(id) as 'cnt'
            from tbl_steelreport
            where steelreports_category_id in ($ids)");
            
            $d = mysql_fetch_array($c);
            $catCnt = $d['cnt'];
                    
            if($rptType == 'r')
                $arrCnt['Regular'] = (int)$catCnt;            
            if($rptType == 's')
                $arrCnt['Special'] = (int)$catCnt;            
            if($rptType == 'k')
                $arrCnt['Knowledge'] = (int)$catCnt;   */         
        }
		$arrCnt['all'] = $arrCnt['all'] + $arrCnt['Regular'] + $arrCnt['Special'] + $arrCnt['Knowledge'] ;          
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $arrCnt;
	}
	
	public static function eventsCatCount($filter = array()){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$d = date("Y-m-d");
		if(isset($filter['year']) && $filter['year'] !='')
		   $cond .= " and `start_date` like '%{$filter['year']}-%' ";
		
		if(isset($filter['regionID']) && $filter['regionID'] !='')
		   $cond .= " and `regionID` = '{$filter['regionID']}' ";   
		
		if(isset($filter['commodityID']) && $filter['commodityID'] !='')
		   //$cond .= " and `commodityID` = '{$filter['commodityID']}' ";   
		    $commId = implode(",", $filter['commodityID']);
		   $cond .= " and `commodityID` IN ($commId) ";
		
		   $a = mysql_query("
                SELECT case 
                            when end_date >= '$d' then 'upcoming' 
                            else 'archieve' 
                       end as 'eventStatus', 
                       count(id)  as 'cnt'
				FROM `tbl_events` WHERE 1=1 {$cond} 
				group by eventStatus
            ");
        
        $arrCnt = array();
        while($b = mysql_fetch_array($a)){
            $eventStatus = $b["eventStatus"];    
            $cnt = $b["cnt"];
            
            $arrCnt[$eventStatus] = (int)$cnt;            
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $arrCnt;
	}

    public static function getBookrMarkedCommoditiesOfPrices($memid){ 
         $c = mysql_query("
            SELECT  distinct commodty_name, commodityId 
            FROM     `tbl_exim_master` 
            WHERE   id in (
                SELECT row_id 
            	FROM 	`tbl_user_portfolio` 
            	WHERE 	`user_id` = $memid
            	and 	`type` = 'prices'
            	and		appType = 'SM'
            	and     prices_col in ('fob', 'cnf')
            )
            
            UNION
            
            SELECT  distinct commodty_name, commodityId 
            FROM     `tbl_dom_master` 
            WHERE   id in (
                SELECT row_id 
            	FROM 	`tbl_user_portfolio` 
            	WHERE 	`user_id` = $memid
            	and 	`type` = 'prices'
            	and		appType = 'SM'
            	and     prices_col in ('f')
            )
        ");
        $a = array();
        while($result = mysql_fetch_assoc($c)) {
            $a[] = array(
                "id" => $result['commodityId'],
                "itemName" => $result['commodty_name']
            );
        }
        return $a;
    }

	public static function getBookrMarkedCommoditiesOfInsights($memid){
        $commoIds = qryToCommaSepString("
            SELECT commodityId 
        	FROM 	`tbl_user_portfolio` 
        	WHERE 	`user_id` = $memid
        	and 	`type` = 'intel_insight'
        	and		appType = 'SM'
        ");
        $c = mysql_query("
            select id, itemName
            from	tbl_region_commodity_master
            where id in (
            	$commoIds
            )
        ");
        $a = array();
        while($result = mysql_fetch_assoc($c)) {
            $a[] = array(
                "id" => $result['id'],
                "itemName" => $result['itemName']
            );
        }
        return $a;
        
	}
	
	public static function getReportsBookmarkednt($memid){
	    return mysql_num_rows(mysql_query("SELECT * FROM `tbl_bookmarks` WHERE `section` = 'report' and `memid` = $memid and `status` = 'active'"));
	}
	
	//DEFAULT_REPORTS_LIMIT
	public static function getReportsRows($memid=0, $source='listing', $resourceType="app", $type='default', $filter=array(), $pageType='post', $limit=5, $offset=0, $appType='SM'){
		
		if( isset($filter['app_type']) && $filter['app_type']== 'CM' )
			$appType = 'CM';
		else
			$appType = 'SM';

        $result=array(); 
		$sql = "SELECT  id as category_id, 
		                n.commodityID, 
		                n.orderForRegularRpts, 
		               
		                n.subCommodityID, 
		                n.report as 'viewIndex', 
		                (SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = n.commodityID) as commodityName,
		                (SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = n.subCommodityID) as subCommodityName,  
		                n.regionID, 
		                n.`thumbnail`, 
		                CASE 
							WHEN f_special_regular = 's' THEN ''
							ELSE (SELECT file FROM tbl_steelreport
							where steelreports_category_id = n.id
							and FROM_UNIXTIME(date,'%Y-%m-%d') < date_sub(now(), interval 3 month) 
							order by date desc
							limit 0,1)
						END as sampleFileURL, 
		                n.`rate`, 
		                n.`category`, 
		                n.`f_special_regular`, 
		                n.`order_by_val`, 
		                title, 
		                packageID
		        ";
		                
		$sql .= " FROM `tbl_steelreports_category` n";
		//$sql .= " WHERE n.`id` > 0  and f_special_regular <>'t' ";//and n.id!='25' and  n.id!='20'
		$sql .= " WHERE n.`id` > 0  and f_special_regular <> 't'  and f_special_regular <> 'c' ";//and n.id!='25' and  n.id!='20'
		
		if($resourceType=='app'){
			if(in_array($memid, $GLOBALS['SPLRPT_MEMID_ALLOWED'])!==false ){
				$sql .= " AND (n.`f_special_regular`='r'  or n.id = 5 )";
			}else
				$sql .= " AND (n.`f_special_regular`='r' )";
			$sql .= " AND (showInMobApp=1)";
		}
		$orderBY = "";$bookMarkedIds=array();
		$bookmsrkedRptsCnt = 0;
		if($source!='') {//source
			
			switch($source){
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark':
					$common = new Common();
					$bookMarkedIds = $common->getUserBookmarksV2019($resourceType, $memid, $section='report', $status='', $event_id=0, $offset, $filter);
                    
                    if(isset($filter['renderAt']) && $filter['renderAt'] == 'new_dashboard'){
                        //$bookmsrkedRptsCnt = ceil(count($bookMarkedIds)/2);
                        $bookmsrkedRptsCnt = \apiQuery::getReportsBookmarkednt($memid);
                        $bookmsrkedRptsCnt = ceil($bookmsrkedRptsCnt / 2);
                    }

					if(count($bookMarkedIds)>0)
						$filter['itemID'] = $bookMarkedIds;
					else
						$filter['itemID'] = array(0);
				break;
				
				case 'viewArchive':// by reportID
				break;				
				default: //like listing , mapview and others
				break;
			}			
		}
		
		if(isset($filter['searchTerms']) && !empty($filter['searchTerms'])) {
			$cd = date("Y-m-d");
			$ct = date("H:i:s");
			mysql_query("
				insert into tbl_searches 
				values (
				'',
				'$cd',
				'$ct',
				$memid,
				'reports',
				'" . htmlspecialchars($filter['searchTerms'], ENT_QUOTES) . "',
				'$resourceType'
				)"
			);
			$sql .= " AND (";

			$implode = array();

			$words = explode(' ', trim(preg_replace('/\s+/', ' ', $filter['searchTerms'])));

			foreach ($words as $word) {
				if( $memid == 116707 ){
					$implode[] = '(n.`category` REGEXP "[[:<:]]$word[[:>:]]" OR 
				n.`title` REGEXP "[[:<:]]$word[[:>:]]" OR 
				n.`report` REGEXP "[[:<:]]$word[[:>:]]" )';				
				} else 
					$implode[] = "CONCAT(n.`title`, n.`category`, n.`report`) LIKE '%" . mysql_real_escape_string($word) . "%'";
			}

			if ($implode) {
				$sql .= " " . implode(" AND ", $implode) . "";
			}

			$sql .= ")";
		}   
		
		
		if(isset($filter['authorID']) && $filter['authorID']>0) {	
			$authorID= (int)$filter['authorID'];
			$categoryIds = qryToCommaSepString("select steelreports_category_id from tbl_steelreport where author_id=$authorID ");
			$sql .= " AND n.`id` IN (";
			$sql .= $categoryIds;
			$sql .= ")";			
		}
						
		if(!empty($bookMarkedIds)) {// for a perticular category
			$authorID= (int)$filter['authorID'];
			$categoryIds = qryToCommaSepString("select steelreports_category_id from tbl_steelreport where id IN (".  implode(',', $bookMarkedIds)  .") ");
			if(empty($categoryIds))
				$categoryIds=0;
			$sql .= " AND n.`id` IN (";
			$sql .= $categoryIds;
			$sql .= ")";	
		}
		
		if(isset($filter['reportID']) && !empty($filter['reportID'])) {// for a particular category
			if(is_array($filter['reportID']))
				$sql .= " AND n.`id` IN (" . implode(',',$filter['reportID']) .")";
			else
				$sql .= " AND n.`id` = " . (int)$filter['reportID'];
		}
		
		if($filter['source']=='home_new'){
			$filter['type']='regular';
		}
		
		if(isset($filter['type']) && !empty($filter['type'])) {
			$f_special_regular='0';
			if ($filter['type'] == "regular") {
				$f_special_regular = "r";
			} elseif($filter['type'] == "special") {
				$f_special_regular = "s";
			} elseif($filter['type'] == "knowledge center" || $filter['type'] == "knowledge") {
				$f_special_regular = "k";
			}
			
			$sql .= " AND n.`f_special_regular` = '$f_special_regular'";
		}
		
		if($filter['sliderID']!=''){
			$common = new Common();			
			$sliderRes = $common->getSliderDetails($filter['sliderID']);
			
			if(empty($sliderRes)){								
				$filter['commodityID'] = array(); 
				$filter['regionID'] = array();
			}else{
				if($sliderRes['commodityID'])
					$filter['commodityID'] = array($sliderRes['commodityID']); 
				if($sliderRes['regionID'])
					$filter['regionID'] = array($sliderRes['regionID']); 
			}
		}
		
		
        //code added for App - market wise listing 
		if(!empty($filter['selected_market']) && strtolower($resourceType)=='app'){
		//and parentID=0
            $qry =  "select 
            GROUP_CONCAT(id) as commodities
            from tbl_region_commodity_master where FIND_IN_SET('".$filter['selected_market']."',f_market)  and itemtype='commodity' ";        
            $res = mysql_query($qry);
            $row = mysql_fetch_assoc($res);
            $market_commodities = $row['commodities'];
            $sql .= " AND (";
				$sql .= " commodityID IN (";
				$sql .=     $market_commodities;
				$sql .= ") OR ";
				$sql .= " subCommodityID IN (";
				$sql .=  $market_commodities;				
				$sql .= ")";				
			$sql .= ")";
		}

        if(isset($filter['selected_market_ids']) && !empty($filter['selected_market_ids'])) {
			$sql .= " AND (";
				$sql .= " `commodityID` IN ('";
				$sql .= implode("', '", $filter['selected_market_ids']);
				$sql .= "')";
			$sql .= " OR ";	
				$sql .= " `subCommodityID` IN ('";
				$sql .= implode("', '", $filter['selected_market_ids']);
				$sql .= "')";
			$sql .= ")";
			
			$sql .= $sql_cod;
		}elseif(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
			$sql .= " AND (";
			foreach($filter['commodityID'] as $k=>$commodityID){
				if( $k> 0 )
					$sql .= " OR ";
				$sql .= " FIND_IN_SET({$commodityID},`commodityID`) > 0 ";
			}
			$sql .= " ) ";
		}
		
		if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {			
		}
		if($appType=='CM'){
			//$web_domain = $appType=='CM' ? "coalmint.com" : "steelmint.com";
		} else {
			$sql .= " and n.id not in (40,41,42,43) ";
			//$web_domain = "steelmint.com";
		}	
		
		if($web_domain != '') {
			//$sql .= " AND n.`website` LIKE '%" . mysql_real_escape_string($web_domain) . "%'";
		}
		
		$sort_data = array(
			'n.`post_title`',
			'n.`author_name`',
			'n.`post_date`',
			'n.`created_at`',
			'n.`most_read`',
			't.`tags`',
			'n.`created_at`'
		);

		if (isset($filter['sort']) && in_array($filter['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $filter['sort'];
			if(isset($filter['order']))
				$sql .= " " . $filter['order'];
		}elseif($orderBY!=''){
			$sql .= " ORDER BY " . $orderBY;
		}else {
			$sql .= " ORDER BY CASE n.id
						WHEN 1 then 1
						WHEN 2 then 2
						WHEN 3 then 3
						WHEN 7 then 3
						WHEN 4 then 4
						WHEN 17 then 5
						ELSE 99
					END";
		}
		//if(!empty($bookMarkedIds)) {
		 //   $sql .= " limit $offset, 2 ";
		//}
		
		if( isset($filter['debug']) && $filter['debug']== 2 ){
		    echo $sql;
		}
		
		$results = mysql_query($sql) or die ('Error: ' . mysql_error().$sql);
		
		if($pageType=='post')
			$user = new User($memid, $appType);
		
		$final_sql = array();
		
		if($memid) {
			$portfolioCol = ", (SELECT COUNT(up.`id`) FROM `tbl_user_portfolio` up WHERE up.`user_id` = '" . $memid . "' AND up.`row_id` = n.`id` AND up.`type` = 'report' limit 1) as portfolio";
		} else {
			$portfolioCol = ", 0 as portfolio";
		}
		$_condition='';
		if($results != false && mysql_num_rows($results) > 0) {
			if(isset($filter['itemID'])) {
				if(is_array($filter['itemID']))
					$_condition .= " AND n.`id` IN (" . implode(',', $filter['itemID']) .")";
				else
					$_condition .= " AND n.`id` = " . (int)$filter['itemID'];
			}
			
			if(($source=='bookmarks' || $source=='bookmark') && !empty($bookMarkedIds)){ 
				$_condition = " AND n.`id` IN (" . implode(',', $bookMarkedIds) .")";
				//$limit = 2;
			}	
			
			if($source=='bookmarks' || $source=='bookmark') {
			}elseif($source=='viewArchive' || isset($filter['reportID']) ) {
				$limitCond = " LIMIT " . (int)$offset . ", " . (int)$limit;
				$_innerPage = true;
			}else{
				$limitCond  = " LIMIT 0, 1" ;
				$_innerPage = false;
			}
			
			while($result = mysql_fetch_assoc($results)) {
				$f_special_regular = "";
				if ($result['f_special_regular'] == "r") {
					$f_special_regular = "regular";
				} else if ($result['f_special_regular'] == "s") {
					$f_special_regular = "special";
				} else if ($result['f_special_regular'] == "kc" || $result['f_special_regular'] == "k") {
					$f_special_regular = "knowledge center";
				}else
					$f_special_regular = $result['f_special_regular'];
				
				$db_value_f_special_regular = $result['f_special_regular'];
				$_dt_col = "FROM_UNIXTIME(date,'%d %M %Y') as fin_date";
				
				$final_sql[] = "(SELECT steelreports_category_id, n.id itemID, file, 
					'" . $result['sampleFileURL'] . "'  as sampleFileURL
					, `title` , `category`, $_dt_col, 
					CASE cover_image
						WHEN '' THEN '" . $result['thumbnail'] . "' 
						ELSE cover_image
					END as thumbnail
					,'" . $result['rate'] . "' as rate
					,'$f_special_regular' as f_special_regular, 
					'$db_value_f_special_regular' as db_value_f_special_regular, 
					'" . $result['orderForRegularRpts'] . "' as orderForRegularRpts, 
					
					'" . $result['order_by_val'] . "' as order_by_val, 
					'" . $result['commodityName'] . "' as commodityName, 
					'" . $result['subCommodityName'] . "' as subCommodityName, 
					'" . $result['commodityID'] . "' as commodityID, 
					'" . $result['subCommodityID'] . "' as subCommodityID, 
					timeToRead, 
					'$pageType' as pageType, 
					'" . addslashes($result['viewIndex']) . "' as viewIndex, 
					'" . $result['packageID'] . "' as packageID,
					rm.id  as author_id, rm.RM_name as author_name, rm.RM_email as author_email, rm.imageURL as author_imageURL, rm.facebookId as author_facebookId, rm.twitterId as author_twitterId, rm.linkedIn as author_linkedIn ,rm.details as aboutAuthor					
					,(select id from tbl_bookmarks as b where n.id=b.item_id and b.memid=$memid and section='report'  and status='active'  limit 1) as isBookmarked
					$portfolioCol
					FROM tbl_steelreport as n
					left outer join 
					tbl_rel_manager rm
					ON rm.id = n.author_id
					
					WHERE steelreports_category_id = " . $result['category_id'] . " 
					" . $_condition . "
					ORDER BY date desc
					$limitCond) ";
			}//" . $filter['order'] . "
		}
		
		if(!empty($final_sql)) {
			$sql = implode(" UNION ", $final_sql);
		}
	
		$sql = str_replace("fin_date,", "fin_date,date as 'finDate',", $sql);
		///$sql = str_replace("fin_date,", "fin_date,date as 'finDate',", $sql) . " order by finDate desc";
			
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($filter), $sql, "</pre>";
            echo "pty:" . $pageType;
          
        } 

		$query = mysql_query($sql) or die(mysql_error());
		$region='';$regionCnt = 0;
		$result = array();
		
		while($row = mysql_fetch_assoc($query)){ 
						
			//if($pageType=='post'){
			if($pageType=='post'){
                if(in_array($memid, $GLOBALS['SPLRPT_MEMID_ALLOWED'])!==false && $row['steelreports_category_id']==5){
					$isAccessible = -1;
				}else{
                     if(isset($filter['itemID'])) {
                        //handle blank selected_market case 
                        if(isset($filter['debug']) && $filter['debug'] == 1){
                            echo "Commodity===>".$row['commodityID'];
                        }
                        if(empty($filter['selected_market']) && $resourceType=='app' && !empty($memid)){                        
                            $filter['selected_market'] =  $user->getMarketForAPPByItemID($resourceType,0,'reports',array($row['commodityID']));                
                        }
                          if(isset($filter['debug']) && $filter['debug'] == 1){
                            echo "Market===>". $filter['selected_market'] ;
                        }
                    }
				
					$isAccessible =  $user->isAccessible(
					                            $resourceType, 
					                            $section='Report_'.$row['db_value_f_special_regular'], 
					                            $itemID=$row['itemID'], 
					                            $itemDate=date("Y-m-d", strtotime($row['fin_date'])), 
					                            $row['steelreports_category_id'], 
					                            $filter['selected_market']
					                       );
				}
				if(isset($filter['debug']) && $filter['debug'] == 1) {
					echo '<br>'.$row['title']."==>isacc".$isAccessible.'---'.$row['steelreports_category_id'].'--'.date("Y-m-d", strtotime($row['fin_date'])).'--'.'Report_'.$row['db_value_f_special_regular'].'===>'.$row['file'];
				} 
				//print_r(session()->all());
				if($isAccessible==-1){
					$row['pageType']='post'; 
				}else{
					$row['pageType']='pre';
				}
			}
			
			//$result['itemId'] = strval($row['post_id']);
			
			///echo $row['f_special_regular'] == "special" ? encrypt_decrypt('encrypt',"memid=".$memid."&itemID=".$row['itemID']);
			//$mainFileUrl = BASEURL."reports/".$row['file'];
			$mainFileUrl = BASEURL."reports_PDFs/".$row['file'];
			
			if(strtolower($resourceType)=="web"){
				///$mainFileUrl = $row['f_special_regular'] == "special" ? BASEURL.'downloads_rpt.php?splrpt='.base64_encode("memid=".$memid."&itemID=".$row['itemID']):BASEURL."reports/".$row['file'];
				//$mainFileUrl = BASEURL.'downloads_rpt.php?path=reports&download_file=' . BASEURL."reports/".$row['file'];
				//$mainFileUrl = BASEURL.'downloads_rpt.php?path=reports&download_file=' . $row['file'];
				$mainFileUrl = BASEURL.'downloads_rpt.php?path=reports_PDFs&download_file=' . $row['file'];
			}
			$row['title'] = html_entity_decode($row['title'], ENT_QUOTES);			
			$fileDir = preg_replace('/[^A-Za-z0-9\-\_]/', '',str_replace(" ", "_", $row['category']));
			$fileDir = str_replace("_", " ", $fileDir);
			$coverImageURL ='';
			if($row['thumbnail']!='')
                $coverImageURL = BASEURL."images/reports/".$fileDir."/".$row['thumbnail'];
			$result[] = array(
                "itemID" => (int)$row['itemID'],
                "reportID" => (int)$row['steelreports_category_id'],
                "orderForRegularRpts" => (int)$row['orderForRegularRpts'],
                
                "packageID" => (int)$row['packageID'],
                //"coverImageURL" => str_replace("https://www.steelmint.com","https://img.steelmint.com", BASEURL."images/reports/".$row['category']."/".$row['thumbnail']),
                //"coverImageURL" => str_replace("https://www.steelmint.com","https://img.steelmint.com", BASEURL."images/reports/".$fileDir."/".$row['thumbnail']),
				"coverImageURL" => $coverImageURL,
                
                //"title" =>($_innerPage==true)?ucwords(strtolower($row['title'])):ucwords(strtolower($row['category'])),
                "title" =>$row['title'],
               // "datePublished" => date("Y-m-d", strtotime($row['fin_date'])),
                "datePublished" => date("d M Y", strtotime($row['fin_date'])),
                "datePublished_formatted" => date("Y-m-d", strtotime($row['fin_date'])),
                "timeToRead" => ($row['pageType']=='pre' ? "hidden" : $row['timeToRead']),
                
                "commodityName" => $row['commodityName'],
                "subCommodityName" => $row['subCommodityName'],
                "commodityID" => $row['commodityID'],
                "subCommodityID" => $row['subCommodityID'],
                
               // "mainFileUrl" =>($row['pageType']=='pre' ? BASEURL."app_webview_pages/unauthorised_action.php" : $mainFileUrl ),
                "mainFileUrl" =>($row['pageType']=='pre' ? "hidden"  : $mainFileUrl ),
                //"sampleFileURL" => $row['sampleFileURL']!='' ? BASEURL."reports/sampleURLs/".$row['sampleFileURL'] : "",
                //"sampleFileURL" => $row['sampleFileURL']!='' ? BASEURL."reports/".$row['sampleFileURL'] : "",
                "sampleFileURL" => $row['sampleFileURL']!='' ? BASEURL."reports_PDFs/".$row['sampleFileURL'] : "",
                "typeOfReport" => $row['f_special_regular'],
               /// "description" => removeMSWordattributes(html_entity_decode($row['viewIndex'], ENT_QUOTES)),
                "description" => utf8_decode(stripslashes(html_entity_decode($row['viewIndex']))),
                //"isBookmarked" => ($row['pageType']=='post' ? ($row['isBookmarked']!='' ? "y" : "n") : "n"),
                "isBookmarked" => $row['isBookmarked']!='' ? "y" : "n",
                "isAddedToPortfolio" =>($row['pageType']=='post' ? ($row['portfolio']== 1? 'y': 'n') : "n"),
				'authorDetails' => array(
									"authorID"=>intval($row['author_id']),
									"imageURL"=>$row['author_imageURL'],
									"name"=>$row['author_name'],
									"emailId"=>$row['author_email'],
									"socialAccounts"=>array(
										'facebook'=>$row['author_facebookId'],
										'twitter'=>$row['author_twitterId'],
										'linkedIn'=>$row['author_linkedIn']
									),
									"aboutAuthor"=>$row['aboutAuthor']
								)
            );
			//$news[] = $result;
			
		}
		
		if($type=='default'){
			//json file $news;
		}
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>" . print_r($result) . "</pre>";
        } 

		
        if(isset($filter['renderAt']) && $filter['renderAt'] == 'new_dashboard') {
            $finres = array();
            $finres["dataValue"] = $result;
            $finres["cntValue"] = $bookmsrkedRptsCnt;
            
            return $finres;
        } else {
            return $result;
        }
		
		return $result;
    }	

	///logistics
		
	public static function getRailwayMovementRows_old($memid=0, $resourceType="app", $filter=array(), $pageType='post', $appType='SM', $limit=DEFAULT_LIMIT, $offset=0){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$sql = "
				SELECT 	trp.zone as zone_code, 
						trp.division,
						trp.f_date, 
						trp.load_stn, COALESCE(ta_load.f_full_form, trp.load_stn) as load_station, 
						trp.unload_stn, COALESCE(ta_unload.f_full_form, trp.unload_stn) as unload_station, 
						trp.consignor, COALESCE(ta_consignor.f_full_form, trp.consignor) as consignor_full, 
						trp.consignee, COALESCE(ta_consignee.f_full_form, trp.consignee) as consignee_full,
						CASE
							WHEN (trp.consignor = 'JSPL' or trp.consignor = 'JSPK') AND trp.consignee not in ('JSPL','JSPK') THEN 'Pellet' 
							WHEN trp.consignor = 'JSPK' AND trp.consignee not in ('JSPL','JSPK') THEN 'Pellet'
							WHEN trp.consignor = 'BRAH' AND trp.consignee <> 'BRAH' THEN 'Pellet'
							WHEN trp.consignor = 'AISL' AND trp.consignee <> 'AISL' THEN 'Pellet'
							WHEN trp.consignor = 'BPSL' AND trp.consignee <> 'BPSL' AND trp.load_stn = 'SBPY' THEN 'Pellet'
							WHEN trp.consignor = 'MSPI' AND trp.consignee <> 'MSPI' AND trp.load_stn = 'PRNR' THEN 'Pellet'
							WHEN trp.consignor = 'OML' 	AND trp.consignee <> 'OML' 	AND trp.load_stn = 'PAPK' THEN 'Pellet'
							WHEN trp.consignor = 'ARSL' AND trp.consignee <> 'ARSL' THEN 'Pellet'
							ELSE 'Iron Ore'
						END as commodity,
						CASE
							WHEN trp.zone = 'SE'  THEN 'SOUTH EAST'
							WHEN trp.zone = 'SW'  THEN 'SOUTH WEST'
							WHEN trp.zone = 'ECO' THEN 'EAST COAST'
						END as zone

				FROM tbl_railway_programme as trp
				left outer join tbl_abbreviation as ta_load ON trp.load_stn = ta_load.f_abbr AND ta_load.`f_type` = 'sttn_from_destn'
				left outer join tbl_abbreviation as ta_unload ON trp.unload_stn = ta_unload.f_abbr AND ta_unload.`f_type` = 'sttn_from_destn'
				left outer join tbl_abbreviation as ta_consignor ON trp.consignor = ta_consignor.f_abbr AND ta_consignor.`f_type` = 'CNSR_CNSG'
				left outer join tbl_abbreviation as ta_consignee ON trp.consignee = ta_consignee.f_abbr AND ta_consignee.`f_type` = 'CNSR_CNSG'				
			";
		$sql .= " WHERE trp.`id` > 0 ";
		
		$sql_cod = '';
		if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
			$sql_cod .= " AND (";
				$sql_cod .= " `commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodityID']);
				$sql_cod .= "')";
			$sql_cod .= " OR ";	
				$sql_cod .= " `sub_commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodityID']);
				$sql_cod .= "')";
			$sql_cod .= ")";
			
			$sql .= $sql_cod;
		}
		
		if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
			$sql_cod .= " AND `zone` IN ('";
			$sql_cod .= implode("', '", $filter['regionID']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
		}
		
		if(isset($filter['onDate'])) {
			$onDate = $filter['onDate'];
			$sql .= " AND `f_date` = '$onDate')";
		}else{
			$sql1 = "
				SELECT max(f_date) as onDate
				FROM tbl_railway_programme
				WHERE `id` > 0
				$sql_cod
				ORDER BY f_date DESC
			";
			$rs = mysql_query($sql1);			
			$row = mysql_fetch_array($rs,MYSQL_ASSOC);
			$onDate=$row['onDate'];			
		}
		
		if($onDate=='')
				$onDate = $GLOBALS['currDate'];
			
		$sql .= " AND `f_date` = '". $onDate. "'";
		$sql .= " ORDER BY commodity";
		
		/* if($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		else
			$limit = DEFAULT_LIMIT; 
		
		$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;*/
		
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($filter), $sql, "</pre>";
          
        }
        
		
		if($filter['isDownload']==1){
			$folder_name='rMovement_'.$memid.date('Ymd_hms');
			/* if(!is_dir('/home/steelmin/public_html/api/public/logistics')){
				mkdir('/home/steelmin/public_html/api/public/logistics');
			}
			///$file_path_location = 'Download/Statistics/'.$folder_name;
			$file_path_location = '/home/steelmin/public_html/api/public/logistics/'.$folder_name; */
			$file_path_location = storage_path('logistics').'/'.$folder_name;
			mkdir($file_path_location);
			
			$headings = array();
			if ($result = mysql_query($sql) or die(mysql_error())) {
				/** Create a new PHPExcel object 1.0 */
				$str='';
				$num_fields = mysql_num_fields($result);
				for ($i = 0; $i < $num_fields; $i++) {
					$hdngName = mysql_field_name($result,$i);
					//if( "id" != $hdngName )
					$headings[] = $hdngName;
				}			
			}
			$saving_name = $memid.date('Ymd_hms').'.csv';
			/** Loop through the result set 1.0 */
			
			$fileHandle = fopen( $file_path_location."/".$saving_name, 'a'); 
			fputcsv( $fileHandle, $headings ); 
			
			while ($row = mysql_fetch_row($result)) {
				fputcsv( $fileHandle, $row ); 
			}
			
			//Added footer 
			$footerdata_common = "DISCLAIMER:- WHILE EXTREME CARE HAS BEEN TAKEN IN THE PREPARATION OF THIS REPORT, NO LIABILITY CAN BE ACCEPTED FOR ANY LOSS INCURRED IN ANY WAY WHATSOEVER BY ANY PERSON RELYING ON THE INFORMATION CONTAINED HEREIN.";
			fputcsv( $fileHandle, array($footerdata_common)); 
			
			fclose( $fileHandle ); 
			
			$zip_file = $folder_name .".zip";
			$zip = new \ZipArchive();
			$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

			//$path = storage_path('logistics');
			$path = $file_path_location;
			$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path));
			foreach ($files as $name => $file)
			{
				// We're skipping all subfolders
				if (!$file->isDir()) {
					$filePath     = $file->getRealPath();

					// extracting filename with substr/strlen
					$relativePath = substr($filePath, strlen($path) + 1);

					$zip->addFile($filePath, $relativePath);
					
				}
			}
			$zip->close();
			
			if(file_exists($file_path_location)){//delete files after zip
				if (\File::exists($file_path_location)) \File::deleteDirectory($file_path_location);
			}
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $file_path = BASEURL . "api/public/" . $zip_file;
			
			//return response()->download($zip_file);
			/*try{
			$zipname = $folder_name .".zip";
	
			zipFile($file_path_location, '/home/steelmin/public_html/api/public/logistics/'.$zipname, true);
			}catch(Exception $e) {
			  echo 'Message: ' .$e->getMessage();
			}
			return $file_path = BASEURL . "api/public/logistics/" . $zipname;
			*/
		}else{
			$query = mysql_query($sql);
			$region='';$regionCnt = 0;
			
			$result = array();	
			while($row = mysql_fetch_assoc($query)){
				$row['consignor'] = $pageType=='pre' ? "hidden" : $row['consignor'];
				$row['consignor_full'] = $pageType=='pre' ? "hidden" : $row['consignor_full'];
				$row['consignee'] = $pageType=='pre' ? "hidden" : $row['consignee'];
				$row['consignee_full'] = $pageType=='pre' ? "hidden" : $row['consignee_full'];
				$result['items'][] = $row;			
			}
			$result['onDate']=$onDate;
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $result;
		}
		
	}
	
	//railway movement $memid, $resourceType, $filters, $accessType, $this->appType
	public static function getRailwayMovementRows($memid=0, $resourceType="app", $filter=array(), $pageType='post', $appType='SM', $limit=DEFAULT_LIMIT, $offset=0){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$sql = "
				SELECT 	trp.zone as zone_code,
						
						trp.division,COALESCE(ta_division.f_full_form, trp.division) as division_full,
						trp.f_date, 
						trp.load_stn, COALESCE(ta_load.f_full_form, trp.load_stn) as load_station, 
						trp.unload_stn, COALESCE(ta_unload.f_full_form, trp.unload_stn) as unload_station, 
						trp.consignor, COALESCE(ta_consignor.f_full_form, trp.consignor) as consignor_full, 
						trp.consignee, COALESCE(ta_consignee.f_full_form, trp.consignee) as consignee_full,
						CASE
							WHEN (trp.consignor = 'JSPL' or trp.consignor = 'JSPK') AND trp.consignee not in ('JSPL','JSPK') THEN 'Pellet' 
							WHEN trp.consignor = 'JSPK' AND trp.consignee not in ('JSPL','JSPK') THEN 'Pellet'
							WHEN trp.consignor = 'BRAH' AND trp.consignee <> 'BRAH' THEN 'Pellet'
							WHEN trp.consignor = 'AISL' AND trp.consignee <> 'AISL' THEN 'Pellet'
							WHEN trp.consignor = 'BPSL' AND trp.consignee <> 'BPSL' AND trp.load_stn = 'SBPY' THEN 'Pellet'
							WHEN trp.consignor = 'MSPI' AND trp.consignee <> 'MSPI' AND trp.load_stn = 'PRNR' THEN 'Pellet'
							WHEN trp.consignor = 'OML' 	AND trp.consignee <> 'OML' 	AND trp.load_stn = 'PAPK' THEN 'Pellet'
							WHEN trp.consignor = 'ARSL' AND trp.consignee <> 'ARSL' THEN 'Pellet'
							ELSE 'Iron Ore'
						END as commodity,
						CASE
							WHEN trp.zone = 'SE'  THEN 'SOUTH EAST'
							WHEN trp.zone = 'SW'  THEN 'SOUTH WEST'
							WHEN trp.zone = 'ECO' THEN 'EAST COAST'
							WHEN trp.zone = 'CR' THEN 'CENTRAL RAILWAYS'
							WHEN trp.zone = 'SC' THEN 'SOUTH CENTRAL'
                            WHEN trp.zone = 'SEC' THEN 'SOUTH EAST CENTRAL'
                            WHEN trp.zone = 'WC' THEN 'WEST CENTRAL' 
						END as zone

				FROM tbl_railway_programme as trp
				left outer join tbl_abbreviation as ta_load ON trp.load_stn = ta_load.f_abbr AND ta_load.`f_type` = 'sttn_from_destn'
				left outer join tbl_abbreviation as ta_unload ON trp.unload_stn = ta_unload.f_abbr AND ta_unload.`f_type` = 'sttn_from_destn'
				left outer join tbl_abbreviation as ta_consignor ON trp.consignor = ta_consignor.f_abbr AND ta_consignor.`f_type` = 'CNSR_CNSG'
				left outer join tbl_abbreviation as ta_consignee ON trp.consignee = ta_consignee.f_abbr AND ta_consignee.`f_type` = 'CNSR_CNSG'				
				left outer join tbl_abbreviation as ta_division ON trp.division = ta_division.f_abbr AND ta_division.`f_type` = 'dvsn'				
			";
		$sql .= " WHERE trp.`id` > 0 ";
		
		$sql_cod = '';
		if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
			/* $sql_cod .= " AND (";
				$sql_cod .= " `commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodityID']);
				$sql_cod .= "')";
			$sql_cod .= " OR ";	
				$sql_cod .= " `sub_commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodityID']);
				$sql_cod .= "')";
			$sql_cod .= ")"; */
			/* $sql_cod .= " AND (";
				$sql_cod .= " `commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodityID']);
				$sql_cod .= "')";
			
			$sql_cod .= ")"; */
			$sql_cod .= " AND `commodity` IN ('RMSP' , 'ORES', 'IRON ORE') ";
			$sql .= $sql_cod;
		}
		
		if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
			$sql_cod .= " AND `zone` IN ('";
			$sql_cod .= implode("', '", $filter['regionID']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
		}
		////NEW FILTERS
		
		if(isset($filter['commodity']) && !empty($filter['commodity'])) {
           
            if(in_array('ORES', $filter['commodity'])){                
                array_push($filter['commodity'],"RMSP","IRON ORE");
            }
            
			$sql_cod .= " AND `commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodity']);
				$sql_cod .= "')";
			$sql .= $sql_cod;
		}
		
		if(isset($filter['zone']) && !empty($filter['zone'])) {
			$sql_cod .= " AND `zone` IN ('";
				$sql_cod .= implode("', '", $filter['zone']);
				$sql_cod .= "')";
			$sql .= $sql_cod;
		}
		
		if(isset($filter['consignor']) && !empty($filter['consignor'])) {
			$sql_cod .= " AND `consignor` IN ('";
			$sql_cod .= implode("', '", $filter['consignor']);
			$sql_cod .= "')";		
			$sql .= $sql_cod;
		}
		
		if(isset($filter['consignee']) && !empty($filter['consignee'])) {
			$sql_cod .= " AND `consignee` IN ('";
			$sql_cod .= implode("', '", $filter['consignee']);
			$sql_cod .= "')";		
			$sql .= $sql_cod;
		}
		
		if(isset($filter['loadStn']) && !empty($filter['loadStn'])) {
			$sql_cod .= " AND `load_stn` IN ('";
			$sql_cod .= implode("', '", $filter['loadStn']);
			$sql_cod .= "')";		
			$sql .= $sql_cod;
		}
		
		if(isset($filter['unloadStn']) && !empty($filter['unloadStn'])) {
			$sql_cod .= " AND `unload_stn` IN ('";
			$sql_cod .= implode("', '", $filter['unloadStn']);
			$sql_cod .= "')";		
			$sql .= $sql_cod;
		}
		
		if(isset($filter['division']) && !empty($filter['division'])) {
			$sql_cod .= " AND `division` IN ('";
			$sql_cod .= implode("', '", $filter['division']);
			$sql_cod .= "')";		
			$sql .= $sql_cod;
		}
		
		if(isset($filter['onDate']) && !empty($filter['onDate'])) {
			$onDate = $filter['onDate'];
			//$sql .= " AND `f_date` IN ('";
			//$sql .= implode("', '", $filter['onDate']);
		//	$sql .= "')";
		}else{
			$sql1 = "
				SELECT max(f_date) as onDate
				FROM tbl_railway_programme
				WHERE `id` > 0
				$sql_cod
				ORDER BY f_date DESC
			";
			$rs = mysql_query($sql1);			
			$row = mysql_fetch_array($rs,MYSQL_ASSOC);
			$onDate=$row['onDate'];			
		}
		
		if($onDate=='')
				$onDate = $GLOBALS['currDate'];
			
		if(isset($filter['fromDate']) && !empty($filter['fromDate']) && isset($filter['toDate']) && !empty($filter['toDate'])){
			$fromDate = $filter['fromDate'];
			$toDate = $filter['toDate'];
			$sql .= " AND `f_date` >= '". $fromDate. "'";
			$sql .= " AND `f_date` <= '". $toDate. "'";
		}
		else{
			$sql .= " AND `f_date` = '". $onDate. "'";
		}
		$sql .= " ORDER BY commodity,f_date desc";
		
		/* if($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		else
			$limit = DEFAULT_LIMIT; 
		
		$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;*/
		
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($filter), $sql, "</pre>";
          
        }
        
		$query = mysql_query($sql);
		$region='';$regionCnt = 0;
		
		$result = array();	
		while($row = mysql_fetch_assoc($query)){
			$row['consignor'] = $pageType=='pre' ? "hidden" : $row['consignor'];
			$row['consignor_full'] = $pageType=='pre' ? "hidden" : $row['consignor_full'];
			$row['consignee'] = $pageType=='pre' ? "hidden" : $row['consignee'];
			$row['consignee_full'] = $pageType=='pre' ? "hidden" : $row['consignee_full'];
			
			$zone = $row['zone'];
			$commodity = $row['commodity'];
			unset($row['zone']);
			unset($row['commodity']);
			unset($row['zone_code']);
			$result[$zone][$commodity][] = $row;
			
		}
				
		if($filter['isDownload']==1){
			require_once('/home/steelmin/public_html/highchart/PHPExcel-1.7.7/Classes/PHPExcel.php');
			require_once('/home/steelmin/public_html/highchart/PHPExcel-1.7.7/Classes/PHPExcel/IOFactory.php');
			
			$folder_name='rMovement_'.$memid.date('Ymd_hms');
			$file_path_location = storage_path('logistics').'/'.$folder_name;
			mkdir($file_path_location);
		
		//following code commented by tarun on 23-2-2021 as it were not allowing data dnld for php 7.1
			//$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
		//	$cacheSettings = array( 'dir'  => '../../tmp/' // If you have a large file you can cache it optional
		//	);
		//	PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
			
			$headings = array();
			$num_fields = mysql_num_fields($query);
			for ($i = 0; $i < $num_fields; $i++) {
				$hdngName = mysql_field_name($query,$i);
				if( "zone" != $hdngName && "commodity" != $hdngName && "zone_code" != $hdngName )
					$headings[] = ucwords(strtolower(str_replace('_',' ',$hdngName)));
			}
			
			
			foreach($result as $zone=>$_zoneArr){
				$itr=0;
				foreach($_zoneArr as $commodity=>$commodity_arr){
					if($itr==0){
						/** Create a new PHPExcel object 1.0 */
						$objPHPExcel = new PHPExcel();
						$objPHPExcel->setActiveSheetIndex(0);
						$objPHPExcel->getActiveSheet()->setTitle($commodity);
						
						/** Loop through the result set 1.0 */
						$rowNumber = 1; //start in cell 1
						$col = 'A';				
						foreach($headings as $heading) {
							$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
							$objPHPExcel->getActiveSheet()->getStyle($col.$rowNumber)->getFont()->setBold(true);
							$col++;
						}
						$rowNumber += 1;
						
					}else{
						// Add new sheet
						$objWorkSheet = $objPHPExcel->createSheet(); //Setting index when creating
						//$objPHPExcel->setActiveSheetIndex(($i-1));
						$objWorkSheet -> setTitle($commodity);
						$objPHPExcel->setActiveSheetIndexByName($commodity);
						
						
						/** Loop through the result set 1.0 */
						$rowNumber = 1; //start in cell 1
						$col = 'A';
						foreach($headings as $heading) {
							$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
							$objPHPExcel->getActiveSheet()->getStyle($col.$rowNumber)->getFont()->setBold(true);
							$col++;
						}
						$rowNumber += 1;
					}
					
					foreach ($commodity_arr as $row) {
						$col = 'A'; // start at column A
						$flag = 0;
						///print_r($row);die;
						foreach($row as $cell) {
							{
								$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
								$col++;
							}	
						}
						$rowNumber++;						
					}				
					
					$itr++;//next sheet
				}
				// Save as an Excel BIFF (xls) file
				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
				$objWriter->save($file_path_location.'/'.$zone.'.xls');
				$objPHPExcel->disconnectWorksheets();
				//exit;
				unset($objWriter);
				unset($objPHPExcel);
				unset($objWorkSheet); 
			}
			
			$zip_file = $folder_name .".zip";
			$zip = new \ZipArchive();
			$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

			//$path = storage_path('logistics');
			//$path = $file_path_location;
			$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($file_path_location));
			foreach ($files as $name => $file)
			{
				// We're skipping all subfolders
				if (!$file->isDir()) {
					$filePath     = $file->getRealPath();

					// extracting filename with substr/strlen
					$relativePath = substr($filePath, strlen($file_path_location) + 1);

					$zip->addFile($filePath, $relativePath);
					
				}
			}
			$zip->close();
			
			/* if(file_exists($file_path_location)){//delete files after zip
				if (\File::exists($file_path_location)) \File::deleteDirectory($file_path_location);
			} */
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $file_path = BASEURL . "api_bm/public/" . $zip_file;
			
			//return response()->download($zip_file);
			/*try{
			$zipname = $folder_name .".zip";
	
			zipFile($file_path_location, '/home/steelmin/public_html/api/public/logistics/'.$zipname, true);
			}catch(Exception $e) {
			  echo 'Message: ' .$e->getMessage();
			}
			return $file_path = BASEURL . "api/public/logistics/" . $zipname;
			*/
		}else{
			$result['onDate']=date('d M Y', strtotime($onDate));
			if($fromDate!='' && $fromDate!='0000-00-00')
                $result['fromDate']=date('d M Y', strtotime($fromDate));
            if($toDate!='' && $toDate!='0000-00-00')
                $result['toDate']=date('d M Y', strtotime($toDate));
			/* $query = mysql_query($sql);
			$region='';$regionCnt = 0;
			
			$result = array();	
			while($row = mysql_fetch_assoc($query)){
				$row['consignor'] = $pageType=='pre' ? "hidden" : $row['consignor'];
				$row['consignor_full'] = $pageType=='pre' ? "hidden" : $row['consignor_full'];
				$row['consignee'] = $pageType=='pre' ? "hidden" : $row['consignee'];
				$row['consignee_full'] = $pageType=='pre' ? "hidden" : $row['consignee_full'];
				$result['items'][] = $row;			
			}
			$result['onDate']=$onDate; */
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $result;
		}
		
	}
	
	//logistics :- Vessel Lineup
	public static function getVesselLineupRows($memid=0, $resourceType="app", $filter=array(), $pageType='post', $appType='SM', $limit=DEFAULT_LIMIT, $offset=0){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$results = array();
		$maxDateQuery = '';
		$commCond = '';
		
		if( $appType == 'CM' ){
			$commCond = " and commodity = 'coal'  ";
			
		}	
		
		if(isset($filter['source'])  && strtolower($filter['source'])=='sailed'){
			$maxCol="date";
			$tblname="tbl_logistics_shipped_data";
		}else{
			$maxCol="excel_upoad_date_time";
			$tblname="tbl_logistic_data";
		}
		
		$maxDateQuery = "SELECT MAX(sl.`$maxCol`) FROM `$tblname` sl WHERE sl.`id` > 0";
		if((isset($filter['source'])  && strtolower($filter['source'])!='sailed') || !isset($filter['source']))
			$maxDateQuery .= " AND sl.`status` IN ('berth', 'anchorage', 'expected', 'shipped')";
	/*
	case 
					when l.`region`<>'' then l.`region`
					else 'Others'
				End as region,*/
		$sql = "SELECT l.excel_upoad_date_time, l.`commodity`,
				selected_country as region, 
				l.`movement`, l.`load_country`, l.`load_port`, l.`unload_country`, l.`unload_port`, l.`receiver`, l.`qty`, l.`cargo`, l.`vessel_name`, l.`date`, l.`status`, selected_country, shipper, imo,type_of_ships";
		$sql .= ", (SELECT c.`country_code` FROM `tbl_country` c WHERE c.`country` = l.`load_country` limit 1) as load_country_flag";
		$sql .= ", (SELECT c.`country_code` FROM `tbl_country` c WHERE c.`country` = l.`unload_country` limit 1) as unload_country_flag";
		
		if(isset($filter['source'])  && strtolower($filter['source'])=='sailed')
			$sql .= " FROM `$tblname` l";
		else
			$sql .= " FROM `$tblname` l";
		//$sql .= " WHERE l.`id` > 0  $commCond ";
		if($appType=='SM')
			$sql .= " WHERE l.`sm_cm` = 'SM' ";
		else
			$sql .= " WHERE l.`id` > 0 ";
		
			
			
		/* if(isset($filter['commodity']) && !empty($filter['commodity'])) {
			$sql .= " AND l.`commodity` = '" . mysql_real_escape_string($filter['commodity']) . "'";

			$maxDateQuery .= " AND sl.`commodity` = '" . mysql_real_escape_string($filter['commodity']) . "'";
		}

		if(isset($filter['country']) && !empty($filter['country'])) {
			$sql .= " AND l.`selected_country` = '" . mysql_real_escape_string($filter['country']) . "'";

			$maxDateQuery .= " AND sl.`selected_country` = '" . mysql_real_escape_string($filter['country']) . "'";
		}
		
		if(isset($filter['region']) && !empty($filter['region'])) {
			$sql .= " AND l.`region` = '" . mysql_real_escape_string($filter['region']) . "'";

			$maxDateQuery .= " AND sl.`region` = '" . mysql_real_escape_string($filter['country']) . "'";
		} */
		if(isset($filter['source'])  && !empty($filter['source'])) {
		
			if(isset($filter['commodity'])  && !empty($filter['commodity'])) {
				$sql_cod = " AND `commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodity']);
				$sql_cod .= "')";
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
			
			if(isset($filter['vesselSize'])  && !empty($filter['vesselSize'])) {
				$sql_cod = " AND `type_of_ships` IN ('";
				$sql_cod .= implode("', '", $filter['vesselSize']);
				$sql_cod .= "')";
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
			
			if(isset($filter['loadCountry'])  && !empty($filter['loadCountry'])) {
				$sql_cod = " AND `load_country` IN ('";
				$sql_cod .= implode("', '", $filter['loadCountry']);
				$sql_cod .= "')";
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
			
			if(isset($filter['unloadCountry'])  && !empty($filter['unloadCountry'])) {
				$sql_cod = " AND `unload_country` IN ('";
				$sql_cod .= implode("', '", $filter['unloadCountry']);
				$sql_cod .= "')";
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
			
			if(isset($filter['company'])  && !empty($filter['company'])) {
				if (in_array("Export",$filter['movement']) || in_array("Coastal (Load)",$filter['movement']))
				{
					$sql_cod = " AND `shipper` IN ('";
					$sql_cod .= implode("', '", $filter['company']);
					$sql_cod .= "')";
				}else{
					$sql_cod = " AND `receiver` IN ('";
					$sql_cod .= implode("', '", $filter['company']);
					$sql_cod .= "')";
				}
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
			
			if(isset($filter['loadPort'])  && !empty($filter['loadPort'])) {
				$sql_cod = " AND `load_port` IN ('";
				$sql_cod .= implode("', '", $filter['loadPort']);
				$sql_cod .= "')";
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
			
			if(isset($filter['unloadPort'])  && !empty($filter['unloadPort'])) {
				$sql_cod = " AND `unload_port` IN ('";
				$sql_cod .= implode("', '", $filter['unloadPort']);
				$sql_cod .= "')";
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
			
			
			
		}else {///old concept till 09-02-2022 or without source
			$sql_cod='';
			if(isset($filter['commodity'])  && !empty($filter['commodity'])) {
			   if( $appType == 'SM'){
					if( strtolower(implode(",", $filter['commodity'])) == 'coal' && !isset($filter['isCoalmint']) ){
						if( $memid != 120954 && $memid != 120030 )
							$sql_cod .= " and cargo in ('COAL', 'MET COKE', 'COKING COAL', 'COKING','Shipped') ";
						else{
							$sql_cod .= " AND `cargo` IN ('";
							$sql_cod .= implode("', '", $filter['commodity']);
							$sql_cod .= "')";
						}
					}else{
						$sql_cod .= " AND `commodity` IN ('";
						$sql_cod .= implode("', '", $filter['commodity']);
						$sql_cod .= "')";
					}
					$sql .= $sql_cod;
			   }else{
				   $sql_cod .= $commCond;
				   if(strtolower(implode(",", $filter['commodity'])) == 'coal'){
						$sql_cod .= " AND `commodity` IN ('";
						$sql_cod .= implode("', '", $filter['commodity']);
						$sql_cod .= "')";
					}else{
						$sql_cod .= " AND `cargo` IN ('";
						$sql_cod .= implode("', '", $filter['commodity']);
						$sql_cod .= "')";
					}
					
					$sql .= $sql_cod;
			   }			   
				
				/* if( strtolower(implode(",", $filter['commodity'])) == 'coal' && !isset($filter['isCoalmint']) ){
					if( $memid != 120954 && $memid != 120030 )
						$sql_cod .= " and cargo in ('MET COKE', 'COKING COAL') ";
					else{
						$sql_cod .= " AND `cargo` IN ('";
						$sql_cod .= implode("', '", $filter['commodity']);
						$sql_cod .= "')";
					}
				} */
				
				//echo $sql .= $sql_cod;die;
				$maxDateQuery .= $sql_cod;
			} else {
				if($appType == 'CM'){
					$sql_cod .= " and commodity = 'coal'";
				}elseif( $memid != 120954 && $memid != 120030 &&  $appType != 'CM' ){
					//$sql_cod .= " and ((commodity = 'coal' and cargo in ('MET COKE', 'COKING COAL')) || commodity <> 'coal' ) ";
					$sql_cod .= " and commodity = 'iron ore'";
				}else
					$sql_cod .= '';
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}
		}
		
		if(isset($filter['region']) && !empty($filter['region'])) {//region
			$sql_cod = " AND `selected_country` IN ('";
			$sql_cod .= implode("', '", $filter['region']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
			$maxDateQuery .= $sql_cod;
		}
		
		if(isset($filter['movement']) && !empty($filter['movement'])) {
			$sql_cod = " AND `movement` IN ('";
			$sql_cod .= implode("', '", $filter['movement']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
			$maxDateQuery .= $sql_cod; 

		}
		
		if(isset($filter['status']) && !empty($filter['status'])) {
			$sql_cod = " AND `status` IN ('";
			$sql_cod .= implode("', '", $filter['status']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
			$maxDateQuery .= $sql_cod;
		}

		if(isset($filter['cargo']) && !empty($filter['cargo'])) {
			if(is_array($filter['cargo'])){
				$sql_cod = " AND `cargo` IN ('";
				$sql_cod .= implode("', '", $filter['cargo']);
				$sql_cod .= "')";
				
				$sql .= $sql_cod;
				$maxDateQuery .= $sql_cod;
			}else{
				$sql .= " AND l.`cargo` = '" . mysql_real_escape_string(trim($filter['cargo'])) . "'";
			}
		}
		
		/* if(isset($filter['source'])  && strtolower($filter['source'])=='sailed'){
			if(isset($filter['onDate'])) {
				$onDate = $filter['onDate'];
				$sql .= " AND `excel_upoad_date_time` = '$onDate')";
			}else{
				$sql1 = "
					SELECT max(excel_upoad_date_time) as onDate
					FROM tbl_logistics_shipped_data
					WHERE `id` > 0
					$sql_cod
					ORDER BY excel_upoad_date_time DESC
				";
				$rs = mysql_query($sql1);			
				$row = mysql_fetch_array($rs,MYSQL_ASSOC);
				$onDate=$row['onDate'];			
			}
			if($onDate=='')
			$onDate = $GLOBALS['currDate'];
		
			$sql .= " AND `excel_upoad_date_time` = '". $onDate. "'";
		} */
		
		if(isset($filter['fromDate']) && $filter['fromDate'] != '') {
			$sql .= " AND DATE(l.`$maxCol`) >= '" . $filter['fromDate'] . "'";
			if(isset($filter['toDate']) && $filter['toDate'] != '')
				$sql .= " AND DATE(l.`$maxCol`) <= '" . $filter['toDate'] . "'";	
			
		}elseif(isset($filter['onDate'])) {
				$onDate = $filter['onDate'];
				if(isset($filter['source'])  && strtolower($filter['source'])=='sailed')
					$sql .= " AND (l.`date`) like ('".$onDate."')";
				else
					$sql .= " AND l.`excel_upoad_date_time` like '%".$onDate."%'";
		}elseif($maxDateQuery) {
			if(isset($filter['source'])  && strtolower($filter['source'])=='sailed')
                $sql .= " AND (l.`$maxCol`) = ((" . $maxDateQuery . "))";
			elseif(isset($filter['source'])  && strtolower($filter['source'])=='working'){
			
			}
			else
                $sql .= " AND DATE(l.`$maxCol`) = DATE((" . $maxDateQuery . "))";
		}

		$sql .= " GROUP BY l.selected_country, l.commodity, l.`movement`, l.`load_country`, l.`load_port`, l.`unload_country`, l.`unload_port`, l.`receiver`, l.`qty`, l.`cargo`, l.`vessel_name`, l.`status`"; 
		
		$sql .= " ORDER BY ";
		if($appType == 'CM'){ 
			$sql .= " l.date desc, case
					when cargo='NON COKING COAL' then 1
					when cargo='COKING COAL' then 2
					when cargo='COKING' then 2
					when cargo='MET COKE' then 3
					when cargo='PET COKE COAL' then 4
					ELSE 99
				end ,
				";
		}else{
			if(strtolower($filter['source'])=='sailed'){
				$sql .=  "l.date desc,";
			}
		}
		
		
		$sql .= " l.selected_country, l.`movement`, l.`load_country`, l.`unload_country`, l.`status`";

		$query = mysql_query($sql) or die("Error: " . mysql_error().$sql);

		/* if($query != false && mysql_num_rows($query) > 0) {
			while($row = mysql_fetch_assoc($query)) {
				$row['qty'] = is_numeric($row['qty']) ? number_format($row['qty']) : $row['qty'];
				if(strtolower($row['vessel_name']) != 'n/a' && strtolower($row['vessel_name']) != 'na' && !empty(strtolower($row['vessel_name']))) {
					$results[] = $row;
				}
			}
		}

		return $results; */
		
				/* if($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		else
			$limit = DEFAULT_LIMIT; 
		
		$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;*/
		
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>filer:", print_r($filter), $sql, "</pre>";
          
        }
        //return json_encode($filter);
		$query = mysql_query($sql);
		$region='';$regionCnt = 0;
	//	echo "<pre>", print_r($filter), $sql, "</pre>";
		
		
		
		$result = array();$onDate='';$totalqty=0;
		while($row = mysql_fetch_assoc($query)){
			
			//$row['qty'] = $pageType=='pre' ? "hidden" : is_numeric($row['qty']) ? number_format($row['qty']) : $row['qty'];
			
			$row['receiver'] = $pageType=='pre' ? "hidden" : $row['receiver'];
			$row['cargo'] = $pageType=='pre' ? "hidden" : $row['cargo'];
			$row['vessel_name'] = $pageType=='pre' ? "hidden" : $row['vessel_name'];
			
			$region = $row['region'];
			$commodity = $row['commodity']; 
			if($onDate=='' && $filter['isDownload']==0){
				if(isset($filter['source'])  && strtolower($filter['source'])=='sailed'){   
					 $onDate = $row['date'];
				}else{                   
					$onDate = $row['excel_upoad_date_time'];
				}
			$result['onDate']=date('d M Y', strtotime($onDate));
			}
			unset($row['region']);
			unset($row['commodity']);
			unset($row['excel_upoad_date_time']);
			
			
			
			if($filter['isDownload']==1){
				if($pageType!='pre')
					$totalqty += $row['qty'];
				else
					$totalqty="hidden";
				
				unset($row['load_country_flag']);
				unset($row['unload_country_flag']);
				unset($row['selected_country']);
				$row['qty'] = $pageType=='pre' ? "hidden" : is_numeric($row['qty']) ? ($row['qty']) : $row['qty'];
			}else{
				$row['qty'] = $pageType=='pre' ? "hidden" : is_numeric($row['qty']) ? number_format($row['qty']) : $row['qty'];
			}
				
			///if region filter count is one then download by region file and sheets of commodity in that file
			///other wise download by commodity wise file and each file have sheets of region wise
			if(isset($filter['source'])){//new format of code added on 02Mar2022
				
				if(isset($filter['commodity'])  && !empty($filter['commodity'])) {
				if($filter['isDownload']==1)
					$result[$filter['source']][$commodity][] = $row;
				else
					$result[$commodity][] = $row;
                }
                else{
                    if($filter['isDownload']==1)
                        $result[$filter['source']]['All'][] = $row;
                    else
                        $result['All'][] = $row;
                }
				
			}else{					
				if($filter['isDownload']==0 || (isset($filter['regionID']) && count($filter['regionID'])==1)){
					$result[$region][$commodity][] = $row;
				}else{
					$result[$commodity][$region][] = $row;
				}
			}
		}


if(isset($filter['debug']) && $filter['debug'] == 1) {
    echo "<pre>result:";
    print_r($result);
    die;
}
				
		if($filter['isDownload']==1){
			require_once('/home/steelmin/public_html/highchart/PHPExcel-1.7.7/Classes/PHPExcel.php');
			require_once('/home/steelmin/public_html/highchart/PHPExcel-1.7.7/Classes/PHPExcel/IOFactory.php');
			
			$folder_name='vlineup_'.$memid.date('Ymd_hms');
			$file_path_location = storage_path('logistics').'/'.$folder_name;
			mkdir($file_path_location);
		
		//following code commented by tarun on 23-2-2021 as it were not allowing data dnld for php 7.1
			//$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
		//	$cacheSettings = array( 'dir'  => '../../tmp/' // If you have a large file you can cache it optional
		//	);
			//PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
			//PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);
			$headings = array();
			$num_fields = mysql_num_fields($query);
			for ($i = 0; $i < $num_fields; $i++) {
				$hdngName = mysql_field_name($query,$i);
				if( "excel_upoad_date_time" != $hdngName && "load_country_flag" != $hdngName && "commodity" != $hdngName && "unload_country_flag" != $hdngName && "region" != $hdngName && "selected_country" != $hdngName)
					$headings[] = ucwords(strtolower(str_replace('_',' ',$hdngName)));
			}
			

			foreach($result as $zone=>$_zoneArr){
				$itr=0;
				foreach($_zoneArr as $commodity=>$commodity_arr){
					if($itr==0){
						/** Create a new PHPExcel object 1.0 */
						$objPHPExcel = new PHPExcel();
						$objPHPExcel->setActiveSheetIndex(0);
						$objPHPExcel->getActiveSheet()->setTitle($commodity);
						
						/** Loop through the result set 1.0 */
						$rowNumber = 1; //start in cell 1
						$col = 'A';				
						foreach($headings as $heading) {
							$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
							$objPHPExcel->getActiveSheet()->getStyle($col.$rowNumber)->getFont()->setBold(true);
							
							$col++;
						}
						$rowNumber += 1;
						
					}else{
						// Add new sheet
						$objWorkSheet = $objPHPExcel->createSheet(); //Setting index when creating
						//$objPHPExcel->setActiveSheetIndex(($i-1));
						$objWorkSheet -> setTitle($commodity);
						$objPHPExcel->setActiveSheetIndexByName($commodity);
						
						
						/** Loop through the result set 1.0 */
						$rowNumber = 1; //start in cell 1
						$col = 'A';
						foreach($headings as $heading) {
							$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
							$objPHPExcel->getActiveSheet()->getStyle($col.$rowNumber)->getFont()->setBold(true);

							$col++;
						}
						$rowNumber += 1;
					}
					
					foreach ($commodity_arr as $row) {
						$col = 'A'; // start at column A
						$flag = 0;
						///print_r($row);die;
						foreach($row as $cell) {
							{
								$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
								$col++;
							}	
						}
						$rowNumber++;							
					}
					$col = 'A'; 
					foreach($headings as $ii=>$heading) {
						if($ii==0)
							$heading='Grand Total';
						elseif($heading=='Qty')
							$heading=$totalqty;
						else
							$heading="";
						$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
						$objPHPExcel->getActiveSheet()->getStyle($col.$rowNumber)->getFont()->setBold(true);
						$col++;
					}
					
					foreach (range('A', $objPHPExcel->getActiveSheet()->getHighestDataColumn()) as $col) {
						$objPHPExcel->getActiveSheet()
								->getColumnDimension($col)
								->setAutoSize(true);
					} 
					
					$itr++;//next sheet
					
					$rowNumber++;
					$rowNumber++;
					$footerdata_common="Qty in mt
					Source: SteelMint, Port release
					Provisional Data";
					$disclaimer="DISCLAIMER:- WHILE EXTREME CARE HAS BEEN TAKEN IN THE PREPARATION OF THIS REPORT, NO LIABILITY CAN BE ACCEPTED FOR ANY LOSS INCURRED IN ANY WAY WHATSOEVER BY ANY PERSON RELYING ON THE INFORMATION CONTAINED HEREIN.";
					$objPHPExcel->getActiveSheet()->setCellValue("A".($rowNumber),$footerdata_common);							
					$objPHPExcel->getActiveSheet()->mergeCells("A".($rowNumber).":".($col). ($rowNumber));							
					$style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::VERTICAL_TOP,  ));
					$objPHPExcel->getActiveSheet()->getStyle("A".($rowNumber).":".($col). ($rowNumber))->applyFromArray($style);
					///$objPHPExcel->getActiveSheet()->getStyle("A".($rowNumber).":".($col). ($rowNumber))->getFont()->setBold(true);
					
					$objPHPExcel->getActiveSheet()->getRowDimension($rowNumber)->setRowHeight(60); 
					$objPHPExcel->getActiveSheet()->getStyle('A'.$rowNumber)->getAlignment()->setWrapText(true);
					
					$rowNumber++;	
					$rowNumber++;
					$objPHPExcel->getActiveSheet()->setCellValue("A".($rowNumber),$disclaimer);							
					$objPHPExcel->getActiveSheet()->mergeCells("A".($rowNumber).":".($col). ($rowNumber));							
					$style = array('alignment' => array('horizontal' => PHPExcel_Style_Alignment::VERTICAL_TOP,  ));
					$objPHPExcel->getActiveSheet()->getStyle("A".($rowNumber).":".($col). ($rowNumber))->applyFromArray($style);
					
					$objPHPExcel->getActiveSheet()->getRowDimension($rowNumber)->setRowHeight(40); 
					$objPHPExcel->getActiveSheet()->getStyle('A'.$rowNumber)->getAlignment()->setWrapText(true);
					
					
				}
				
				// Save as an Excel BIFF (xls) file
				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
				
				$objWriter->save($file_path_location.'/'.$zone.'.xls');
				$objPHPExcel->disconnectWorksheets();
				//exit;
				unset($objWriter);
				unset($objPHPExcel);
				unset($objWorkSheet); 
			}
			
			$zip_file = $folder_name .".zip";
			$zip = new \ZipArchive();
			$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

			//$path = storage_path('logistics');
			//$path = $file_path_location;
			$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($file_path_location));
			foreach ($files as $name => $file)
			{
				// We're skipping all subfolders
				if (!$file->isDir()) {
					$filePath     = $file->getRealPath();

					// extracting filename with substr/strlen
					$relativePath = substr($filePath, strlen($file_path_location) + 1);

					$zip->addFile($filePath, $relativePath);
					
				}
			}
			$zip->close();
			
			/* if(file_exists($file_path_location)){//delete files after zip
				if (\File::exists($file_path_location)) \File::deleteDirectory($file_path_location);
			} */
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $file_path = BASEURL . "api_bm/public/" . $zip_file;
			
			//return response()->download($zip_file);
			/*try{
			$zipname = $folder_name .".zip";
	
			zipFile($file_path_location, '/home/steelmin/public_html/api/public/logistics/'.$zipname, true);
			}catch(Exception $e) {
			  echo 'Message: ' .$e->getMessage();
			}
			return $file_path = BASEURL . "api/public/logistics/" . $zipname;
			*/
		}else{
			///$result['onDate']=$onDate;
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $result;
		}
		
	}
	
	//logistics :- Vessel Freight
	public static function getVesselFreightRows($memid=0, $resourceType="app", $filter=array(), $pageType='post', $appType='SM', $limit=DEFAULT_LIMIT, $offset=0){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$assessments = [
			'D'	=>	'Daily',
			'W'	=>	'Weekly',
			'M'	=>	'Monthly',
			'Y'	=>	'Yearly'
		];

		//$prices = array();
		//$graph_data = array();
		
		$commodityCond = '';
		/*if( $appType == 'CM' || $filter['selected_market']=='coal' )
			$commodityCond = " AND em.item = 'coal' ";
        */

		$sql = "SELECT em.`id`, em.`commodity`, em.`f_grade`, em.`load_country`, em.`unload_country`, em.`load_port`, em.`unload_port`, em.`f_logistics_route_id`, em.`cargo_intake`, em.`assessment`, s.`f_date`";//, s.`updated_on`
		if($filter['isDownload']==0){
			$sql .= ", (SELECT c.`country_code` FROM `tbl_country` c WHERE c.`country` = em.`load_country` limit 1) as load_country_flag";
			$sql .= ", (SELECT c.`country_code` FROM `tbl_country` c WHERE c.`country` = em.`unload_country` limit 1) as unload_country_flag";
		}
		$sql .= " FROM `tbl_exim_master` em";
		$sql .= " LEFT JOIN `tbl_steelprices` s ON(em.`id` = s.`relation_id`)";

		$sql .= " WHERE em.`id` > 0";
		$sql .= " AND em.`category` = 'Logistics' $commodityCond  ";
		
		$sql_cod = '';
		$c_name = implode("', '", $filter['commodity']);
		if(isset($filter['commodity'])  && !empty($filter['commodity'])) {
			/* $sql_cod .= " AND (";
				$sql_cod .= " `commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodityID']);
				$sql_cod .= "')";
			$sql_cod .= " OR ";	
				$sql_cod .= " `sub_commodity` IN ('";
				$sql_cod .= implode("', '", $filter['commodityID']);
				$sql_cod .= "')";
			$sql_cod .= ")"; */
			$sql_cod .= " AND ( `commodty_name` IN ('$c_name') OR `sub_commodty_name` IN ('$c_name') OR `sub_sub_commodty_name` IN ('$c_name')  OR `item` IN ('$c_name')  )";
		//	$sql_cod .= implode("', '", $filter['commodity']);
		//	$sql_cod .= "')";
			
			$sql .= $sql_cod;
			$maxDateQuery .= $sql_cod;
		}
		
		if(isset($filter['vesselSize']) && !empty($filter['vesselSize'])) {
			$sql_cod .= " AND `f_grade` IN ('";
			$sql_cod .= implode("', '", $filter['vesselSize']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
			$maxDateQuery .= $sql_cod;
		}
		
		if(isset($filter['loadCountry']) && !empty($filter['loadCountry'])) {
			$sql_cod .= " AND `load_country` IN ('";
			$sql_cod .= implode("', '", $filter['loadCountry']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
			$maxDateQuery .= $sql_cod;
		}

		if(isset($filter['unLoadCountry']) && !empty($filter['unLoadCountry'])) {
			$sql_cod .= " AND `unload_country` IN ('";
			$sql_cod .= implode("', '", $filter['unLoadCountry']);
			$sql_cod .= "')";
			
			$sql .= $sql_cod;
			$maxDateQuery .= $sql_cod;
		}
		
		/* if(isset($filter['row_id'])) {
			$sql .= " AND em.`id` = " . (int)$filter['row_id'];
		}
		
		if(isset($filter['commodity']) && !empty($filter['commodity'])) {
			if(is_array($filter['commodity'])) {
				$sql .= " AND em.`commodity` IN ('" . implode("', '", $filter['commodity']) . "')";
			} else {
				$sql .= " AND em.`commodity` = '" . mysql_real_escape_string($filter['commodity']) . "'";
			}
		}

		if(isset($filter['load_country']) && !empty($filter['load_country'])) {
			$sql .= " AND em.`load_country` = '" . mysql_real_escape_string($filter['load_country']) . "'";
		}

		if(isset($filter['unload_country']) && !empty($filter['unload_country'])) {
			$sql .= " AND em.`unload_country` = '" . mysql_real_escape_string($filter['unload_country']) . "'";
		}

		if(isset($filter['load_port']) && !empty($filter['load_port'])) {
			$sql .= " AND em.`load_port` = '" . mysql_real_escape_string($filter['load_port']) . "'";
		}

		if(isset($filter['unload_port']) && !empty($filter['unload_port'])) {
			$sql .= " AND em.`unload_port` = '" . mysql_real_escape_string($filter['unload_port']) . "'";
		} */

		if(isset($filter['vessel_size']) && !empty($filter['vessel_size'])) {
			$sql .= " AND em.`f_grade` = '" . mysql_real_escape_string($filter['vessel_size']) . "'";
		}

		if(isset($filter['year']) && !empty($filter['year'])) {
		    $yr = (int)$filter['year'];
		    $st_yr = $yr . '-01-01';
		    $end_yr = $yr . '-12-31'; 
			//$sql .= " AND YEAR(s.`f_date`) = '" . (int)$filter['year'] . "'";
			$sql .= " AND s.`f_date` >= '" . $st_yr . "' and s.`f_date` <= '" . $end_yr . "' ";
		}

		if(isset($filter['month']) && !empty($filter['month'])) {
			$sql .= " AND MONTH(s.`f_date`) = '" . (int)$filter['month'] . "'";
		}

		$sql .= " GROUP BY s.`relation_id`";
		$sql .= " ORDER BY em.`load_country` ASC, em.`unload_country` ASC, em.`load_port` ASC, em.`unload_port` ASC";
		
//		echo $sql;
		
		/* if($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		else
			$limit = DEFAULT_LIMIT; 
		
		$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;*/
		
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($filter), $sql, "</pre>";
          
        }
        
		$region='';$regionCnt = 0;
		
		$result = array();	
		
		$query = mysql_query($sql) or die("Error: " . mysql_error());
		$headings = array();
		
		if($filter['isDownload']==1){
			$num_fields = mysql_num_fields($query);
			for ($i = 0; $i < $num_fields; $i++) {
				$hdngName = mysql_field_name($query,$i);
				if( "id" != $hdngName && "commodity" != $hdngName && "f_logistics_route_id" != $hdngName && "cargo_intake" != $hdngName && "assessment" != $hdngName && "f_date" != $hdngName)
					$headings[] = ucwords(strtolower(str_replace('_',' ',$hdngName)));
			}
			
			
			$headings[] = ' As on Week';
			$headings[] = 'Price in USD/MT';
			/* $headings[] = 'W-o-W';
			$headings[] = 'M-o-M';
			$headings[] = 'Assessment Title'; */
		}
		if($query != false && mysql_num_rows($query)) {
			$rows = array();
			while($row = mysql_fetch_assoc($query)) {
				
				if(!$row['cargo_intake']) {
					$row['cargo_intake'] = 0;
				}

				$sql1 = "SELECT s.`cnf_price`, s.`fob_price`, f_date";
				$sql1 .= " FROM `tbl_steelprices` s";
				$sql1 .= " WHERE s.`relation_id` = " . (int)$row['id'];
				$sql1 .= " GROUP BY DATE(s.`f_date`)";
				$sql1 .= " ORDER BY DATE(s.`f_date`) DESC";
				
				$week_prices = array();
				
				if($filter['isDownload']==0){
					$sql1 .= " LIMIT 0, 5";
					$subQuery = mysql_query($sql1);
					$fdset='';
					if($subQuery != false && mysql_num_rows($subQuery)) {
						while($subRow = mysql_fetch_assoc($subQuery)) {
							$week_prices[] = $subRow['cnf_price'] + $subRow['fob_price'];
							if($fdset==''){
							    $fdset = $subRow['f_date'];
							}
						}
					}
                    $row['f_date'] = $fdset;
					$row['price'] = (isset($week_prices[0])) ? ($pageType=='pre' ? "hidden" : number_format((float)$week_prices[0], 3, '.', '')) : 0;
					$row['w-o-w'] = (isset($week_prices[0]) && isset($week_prices[1])) ? ($pageType=='pre' ? "hidden" :number_format((float)$week_prices[0] - $week_prices[1], 3, '.', '') ) : 0;
					$row['m-o-m'] = (isset($week_prices[0]) && isset($week_prices[4])) ? ($pageType=='pre' ? "hidden" : number_format((float)$week_prices[0] - $week_prices[4], 3, '.', '')) : 0;

					$row['assessment_title'] = isset($assessments[strtoupper($row['assessment'])]) ? $assessments[strtoupper($row['assessment'])] : '';
					
					$load_country = $row['load_country'];
					$commodity = $row['commodity'];
					unset($row['commodity']);
					
					if(isset($filter['source'])){//new format of code added on 11Mar2022
						$result[$commodity][] = $row;
					}else{					
						$result[$commodity][$load_country][] = $row;//commodity Wise
					}
					
				}else{
					$load_country = $row['load_country'];
					$commodity = $row['commodity'];
					unset($row['commodity']);
					unset($row['f_logistics_route_id']);	
					unset($row['cargo_intake']);
					unset($row['assessment']);
					unset($row['id']);
					
					$sql1 .= " LIMIT 0, 13";
					$subQuery = mysql_query($sql1);
					while($subRow = mysql_fetch_assoc($subQuery)) {
						
						$weekStart = date('d M', strtotime($subRow['f_date'] . ' -6 days'));
						$weekEnd = date('d M', strtotime($subRow['f_date']));
						$row['f_date'] = $weekStart . ' - ' . $weekEnd;;
						$row['price'] = $pageType=='pre' ? "hidden" : $subRow['cnf_price'] + $subRow['fob_price'];
						
						$result[$load_country][$commodity][] =  $row;
					}
					
					///$result[$load_country][$commodity][] = $copyRow;//loadCountry Wise
				}
				///$prices[$row['load_country']][] = $row;
			}

		}
		
		
		/* while($row = mysql_fetch_assoc($query)){
			$row['consignor'] = $pageType=='pre' ? "hidden" : $row['consignor'];
			$row['consignor_full'] = $pageType=='pre' ? "hidden" : $row['consignor_full'];
			$row['consignee'] = $pageType=='pre' ? "hidden" : $row['consignee'];
			$row['consignee_full'] = $pageType=='pre' ? "hidden" : $row['consignee_full'];
			
			$zone = $row['zone'];
			$commodity = $row['commodity'];
			unset($row['zone']);
			unset($row['commodity']);
			unset($row['zone_code']);
			$result[$zone][$commodity][] = $row;
			
		} */
				
		if($filter['isDownload']==1){
			require_once('/home/steelmin/public_html/highchart/PHPExcel-1.7.7/Classes/PHPExcel.php');
			require_once('/home/steelmin/public_html/highchart/PHPExcel-1.7.7/Classes/PHPExcel/IOFactory.php');
			
			$folder_name='Freight_'.$memid.date('Ymd_hms');
			$file_path_location = storage_path('logistics').'/'.$folder_name;
			mkdir($file_path_location);
		
		//following code commented by tarun on 23-2-2021 as it were not allowing data dnld for php 7.1
			//$cacheMethod = PHPExcel_CachedObjectStorageFactory:: cache_to_discISAM;
		//	$cacheSettings = array( 'dir'  => '../../tmp/' // If you have a large file you can cache it optional
		//	);
		//	PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);
			
			///=>shif above			
	if(isset($filter['debug']) && $filter['debug'] == 1) {
	    echo "<pre>";   
	    print_r($result);
	}    
			foreach($result as $zone=>$_zoneArr){
				$itr=0;
				foreach($_zoneArr as $commodity=>$commodity_arr){
					if($itr==0){
						/** Create a new PHPExcel object 1.0 */
						$objPHPExcel = new PHPExcel();
						$objPHPExcel->setActiveSheetIndex(0);
						$objPHPExcel->getActiveSheet()->setTitle($commodity);
						
						/** Loop through the result set 1.0 */
						$rowNumber = 1; //start in cell 1
						$col = 'A';				
						foreach($headings as $heading) {
							$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
							$objPHPExcel->getActiveSheet()->getStyle($col.$rowNumber)->getFont()->setBold(true);
							$col++;
						}
						$rowNumber += 1;
						
					}else{
						// Add new sheet
						$objWorkSheet = $objPHPExcel->createSheet(); //Setting index when creating
						//$objPHPExcel->setActiveSheetIndex(($i-1));
						$objWorkSheet -> setTitle($commodity);
						$objPHPExcel->setActiveSheetIndexByName($commodity);
						
						
						/** Loop through the result set 1.0 */
						$rowNumber = 1; //start in cell 1
						$col = 'A';
						foreach($headings as $heading) {
							$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$heading);
							$objPHPExcel->getActiveSheet()->getStyle($col.$rowNumber)->getFont()->setBold(true);
							$col++;
						}
						$rowNumber += 1;
					}
					
					foreach ($commodity_arr as $row) {
						$col = 'A'; // start at column A
						$flag = 0;
						///print_r($row);die;
						foreach($row as $cell) {
							{
								$objPHPExcel->getActiveSheet()->setCellValue($col.$rowNumber,$cell);
								$col++;
							}	
						}
						$rowNumber++;						
					}				
					
					$itr++;//next sheet
				}
				// Save as an Excel BIFF (xls) file
				$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
				$objWriter->save($file_path_location.'/'.$zone.'.xls');
				$objPHPExcel->disconnectWorksheets();
				//exit;
				unset($objWriter);
				unset($objPHPExcel);
				unset($objWorkSheet); 
			}
			
			$zip_file = $folder_name .".zip";
			$zip = new \ZipArchive();
			$zip->open($zip_file, \ZipArchive::CREATE | \ZipArchive::OVERWRITE);

			//$path = storage_path('logistics');
			//$path = $file_path_location;
			$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($file_path_location));
			foreach ($files as $name => $file)
			{
				// We're skipping all subfolders
				if (!$file->isDir()) {
					$filePath     = $file->getRealPath();

					// extracting filename with substr/strlen
					$relativePath = substr($filePath, strlen($file_path_location) + 1);

					$zip->addFile($filePath, $relativePath);
					
				}
			}
			$zip->close();
			
			/* if(file_exists($file_path_location)){//delete files after zip
				if (\File::exists($file_path_location)) \File::deleteDirectory($file_path_location);
			} */
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $file_path = BASEURL . "api_bm/public/" . $zip_file;
			
			//return response()->download($zip_file);
			/*try{
			$zipname = $folder_name .".zip";
	
			zipFile($file_path_location, '/home/steelmin/public_html/api/public/logistics/'.$zipname, true);
			}catch(Exception $e) {
			  echo 'Message: ' .$e->getMessage();
			}
			return $file_path = BASEURL . "api/public/logistics/" . $zipname;
			*/
		}else{
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $result;
		}
		
	}
	
	public static function getVesselFreightPricesByWeeksForGraph($relation_id=0, $randNum=1, $dateFilter=array())
	{
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$other_cond='';
		if(isset($dateFilter['fromDate'])){
			$other_cond .= " AND f_date >= '".$dateFilter['fromDate']."'";
		}

		if(isset($dateFilter['toDate'])){
			$other_cond .= " AND f_date <= '".$dateFilter['toDate']."'";
		}
		
		$sql = "SELECT s.`cnf_price`, s.`fob_price`, s.`f_date`";
		$sql .= " FROM `tbl_steelprices` s";
		$sql .= " WHERE s.`relation_id` = " . (int)$relation_id;
		if($other_cond)
			$sql .= $other_cond;

		$sql .= " GROUP BY DATE(s.`f_date`)";
		$sql .= " ORDER BY DATE(s.`f_date`) DESC";

		$sql .= " LIMIT 0, 20";

		$query = mysql_query($sql) or die("Error: " . mysql_error() . "<br />" . $sql);

		if($query != false && mysql_num_rows($query)) {
			while($row = mysql_fetch_assoc($query)) {
				$price = ($row['cnf_price'] + $row['fob_price']) * $randNum;

				//$weekStart = date('d M', strtotime($row['f_date'] . ' -6 days'));
				$weekEnd = date('W-Y', strtotime($row['f_date']));
				//$weekEnd = date('d M', strtotime($row['f_date']));

				///$data['prices'][$weekStart . '/' . $weekEnd] = number_format($price, 2);
				///$graphData['x'][] = $weekStart . ' - ' . $weekEnd;
				$graphData['x'][] = 'Week ' . $weekEnd;
				$graphData['y'][] = number_format($price , 2);
			}
		}

		$data['x'] = array_reverse($graphData['x']);
		$data['y'] = array_reverse($graphData['y']);

		///$data['rand'] = $randNum;
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $data;
	}
	
	public static function updatePackageIDForApp($memid=0){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		if($memid){
			$sql = "
				SELECT 	id, memid, f_product, selected_products, amtPaid, f_tenure, f_currency, amount_with_tax_ind 
				FROM 	`tbl_reg_logs` 
				where 	status='active' 
				and 	selected_products = 'Mobile App' 
				and 	f_tenure<>'' 
				and 	memid	=	$memid 
				GROUP by 	f_product, 
							selected_products
				";
			$rArr=array();
			$res = mysql_query($sql) or die(mysql_error().$sql);
			while($row = mysql_fetch_assoc($res,MYSQL_ASSOC))
			{
				$packageID=0;
				$f_tenure = $row['f_tenure'];
				$f_product = $row['f_product'];
				$selected_products = $row['selected_products'];
				$f_currency = $row['f_currency'];
				$amtPaid = $row['amtPaid'];
				$amount_with_tax_ind = $row['amount_with_tax_ind'];
				if($f_tenure=='Free Trial'){
					if($f_product=='MA')
						$packageID=145;
					else
						$packageID=	2015; //earlier: 701
				}elseif($f_product=='MA'){//$selected_products=='Mobile App'
					if($f_currency=='INR' || ($f_currency=='' && ($amtPaid>2000 || $amount_with_tax_ind>2000)))
						$packageID=49;
					elseif($f_currency=='USD' || ($f_currency=='' && ($amtPaid<2000 || $amount_with_tax_ind<2000)))
						$packageID=53;
				}elseif($f_product=='MA_PO'){
					if($f_currency=='INR' || ($f_currency=='' && ($amtPaid>2000 || $amount_with_tax_ind>2000)))
						$packageID=1;
					elseif($f_currency=='USD' || ($f_currency=='' && ($amtPaid<2000 || $amount_with_tax_ind<2000)))
						$packageID=5;
				}elseif($selected_products=='Silver' || $selected_products=='Paid Trial'){
					if($f_currency=='INR' || ($f_currency=='' && ($amtPaid>5000 || $amount_with_tax_ind>5000)))
						$packageID=146;
					elseif($f_currency=='USD' || ($f_currency=='' && ($amtPaid<5000 || $amount_with_tax_ind<5000)))
						$packageID=166;
				}elseif($selected_products=='Gold'){
					if($f_currency=='INR' || ($f_currency=='' && ($amtPaid>10000 || $amount_with_tax_ind>10000)))
						$packageID=386;
					elseif($f_currency=='USD' || ($f_currency=='' && ($amtPaid<10000 || $amount_with_tax_ind<10000)))
						$packageID=396;
				}elseif($selected_products=='Platinum'){
					if($f_currency=='INR' || ($f_currency=='' && ($amtPaid>10000 || $amount_with_tax_ind>10000)))
						$packageID=506;
					elseif($f_currency=='USD' || ($f_currency=='' && ($amtPaid<10000 || $amount_with_tax_ind<10000)))
						$packageID=510;
				}else{
					$packageID = $selected_products;
				}
				
				if($packageID){
						mysql_query("
							UPDATE tbl_reg_logs
							SET prev_selected_products = selected_products
							, selected_products = '$packageID'
							WHERE id = '".$row['id']."'
						");
						updateTbltbl_updated_reg_logs($memid);
				}
				/* $row['packageID']= $packageID;
				$rArr[] = $row; */
				///echo '<br>'.$packageID;
			}
			//return $rArr;
			
		}
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
	}
	
	public static function getIntelInsightsList_old($memid='',$commodityID=array(), $offset=0,$filter_arr=array()){
		//include_once "/home/steelmin/public_html/inc/config1.php";
        $result = array();
		$sorted=array();
        $sql = "select post_id, f_section from tbl_intel_insight_hashmap where f_section <> '' ";
		if(!empty($commodityID) && !in_array("709", $commodityID)) {
			//do nothing	
			$sql .= " AND (";
				$sql .= " commodityID IN (";
				$sql .= implode(",", $commodityID);
				$sql .= ") OR ";
				$sql .= " subCommodityID IN (";
				$sql .= implode(",", $commodityID);
				
				$sql .= ") OR ";
				$sql .= " subsubCommodityID IN (";
				$sql .= implode(",", $commodityID);
				$sql .= ")";
			$sql .= ")";
		}else{
			$commodityID = array(709);//no result
		}
		
				
		$limit = DEFAULT_NEWS_LIMIT;
		$sql .= " ORDER BY post_created_date desc, post_created_time desc ";
		$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		
		if(isset($filter_arr['debug']) && $filter_arr['debug'] == 1) {
            echo "<br /><br /><pre>final sql:", $sql . ' -- ' . $offset . ' -- ' . $limit . ' -- ' . $memid . ' -- ' . $source;
        } 


		
		$res1=mysql_query($sql);
		$ids['intel']=array();
		$ids['insight']=array();
		if(mysql_num_rows($res1)>0){
			while($row=mysql_fetch_assoc($res1))
			{
				$ids[$row['f_section']][] = $row['post_id'];
			}
		}else{
			//include_once "/home/steelmin/public_html/inc/desconfig.php";
			return $result;
		}
		
		/* if($memid == 56350) {
            echo "<pre>", $sql, print_r($ids), "</pre>";
			$filter_intel["debug"] = 1;          
        } */
		
// 		$filter_intel = $filter_arr;
// 		$filter_insight = $filter_arr;
		
		$filter_intel["post_id"] = empty($ids['intel'])?array(0):$ids['intel'];
		$filter_intel["orderBy"] = 'datePublished';
		$filter_intel["dontShowAd"] = 'Y';


        if( $memid != '' )
            $result_intel = self::getIntelRowSet($memid,"app",'',$filter_intel,'post',count($ids['intel']),0,'SM');
        else
            $result_intel = self::getIntelRowSet(0,"app",'',$filter_intel,'pre',count($ids['intel']),0,'SM');
            
        $filter_insight["itemID"] = empty($ids['insight'])?array(0):$ids['insight'];
        $filter_insight["sort"] = 'n.`created_at`';

		if(isset($filter_arr['debug']) && $filter_arr['debug'] == 1) {
            
            echo "rai:" . implode(",", $filter_insight["itemID"]);
            echo "raintel:" . implode(",", $filter_intel["post_id"]);
        } 

    
        if( $memid != '' )
            $result_insight = self::getInsightsRows($memid,'listing','app','default',$filter_insight,'post',count($ids['insight']),0,'SM');
        else
            $result_insight = self::getInsightsRows(0,'listing','app','default',$filter_insight,'pre',count($ids['insight']),0,'SM');

        foreach($result_intel["Intels"] as $k=>$v){
		 $time = strtotime($v['datePublished']);
		  $v['thumbnailType'] = $v['type'];
		  $v['mainImageURL'] = $v['imageUrl'];
		  $v['videoURL'] = $v['videoUrl'];
		  $v['intelOrInsight'] = "Intel";

		  unset($v['type']);unset($v['imageUrl']);unset($v['videoUrl']);
          $sorted[$time]= $v; 
          
        }
		
	
		
        foreach($result_insight as $k=>$v){
            $time = strtotime($v['datePublished']);
            $v['intelOrInsight'] = "Insight";
            $sorted[$time] = $v;   
        }
         
        krsort($sorted,SORT_NUMERIC);
        $count=0;
        foreach($sorted as $k=>$v){
            //if($count >= 10)
            //break;
            $result[] = $v;
            $count++;
        } 
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
        return $result;
    }
	
	
	//added on 17aug 2021 
	 public static function getIntelInsightsList($memid='',$commodityID=array(), $offset=0,$filter_arr=array()){
    //include_once "/home/steelmin/public_html/inc/config1.php";
        $result = array();
		$sorted=array();
		
        $sql = "select post_id, f_section from tbl_intel_insight_hashmap where f_section <> '' ";
        
        if((isset($filter_arr['renderAt']) && $filter_arr['renderAt'] == 'new_dashboard') || (isset($filter_arr['source']) && $filter_arr['source'] == 'portfolio')){
            if( $memid != '' ){
				$sqlTC = "select regionId, commodityID from tbl_user_portfolio where user_id=".$memid." and type='intel_insight' order by id desc limit 1";  
				$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);    
				$temp = mysql_fetch_array($rsTC,MYSQL_ASSOC);					
				if($temp['commodityID']){
					$commodityIDs = $temp['commodityID'];
					$tmpArr = explode(',',$commodityIDs);
					
					/*
					    - check if commodity is passed as a parameter in the API request
					    - filter out common commoidties betwen insight's portfolio of this user and passed ones
					    - if no common commodity found then retirn -123 as commodity so that no result is returned.
					    - else return the common commodity list
					*/
					
					if( isset($filter_arr['commodityID']) and count($filter_arr['commodityID']) > 0 ){
					   $filter_arr['commodityID'] = array_intersect($filter_arr['commodityID'], $tmpArr) ;
					   if( count($filter_arr['commodityID']) == 0 ){
					        $filter_arr['commodityID'] = array(-123);
					    }
					} else {
					    $filter_arr['commodityID'] = $tmpArr;
					}
				}
				if($temp['regionId']){
					$regionIDs = $temp['regionId'];
					$filter_arr['regionID'] = explode(',',$regionIDs);
				}
            }
			
			if(empty($filter_arr['commodityID']) && empty($filter_arr['regionID'])){
				return $result;
			}
        }
        
        /*if(isset($filter_arr['renderAt']) && $filter_arr['renderAt'] == 'new_dashboard'){
            echo "start";
            print_r($filter_arr['commodityID']);
            echo "end";
        }*/
        
        
		if($filter_arr['sliderID']!=''){
			$common = new Common();			
			$sliderRes = $common->getSliderDetails($filter_arr['sliderID']);
			
			if(empty($sliderRes)){								
				$filter_arr['commodityID'] = array(); 
				$filter_arr['regionID'] = array();
			}else{
				if($sliderRes['commodityID'])
					$filter_arr['commodityID'] = array($sliderRes['commodityID']); 
				if($sliderRes['regionID'])
					$filter_arr['regionID'] = array($sliderRes['regionID']); 
			}			
		}
		
		if((!empty($commodityID) && !in_array("709", $commodityID)) || (!empty($filter_arr['commodityID']) && !in_array("709", $filter_arr['commodityID']))) {
			if(empty($commodityID))
				$commodityID =$filter_arr['commodityID'];
			//do nothing	
			$sql .= " AND (";
				$sql .= " commodityID IN (";
				$sql .= implode(",", $commodityID);
				$sql .= ") OR ";
				$sql .= " subCommodityID IN (";
				$sql .= implode(",", $commodityID);
				
				$sql .= ") OR ";
				$sql .= " subsubCommodityID IN (";
				$sql .= implode(",", $commodityID);
				$sql .= ")";
			$sql .= ")";
		}else{
			$commodityID = array(709);//no result
		}
		
		//code added for App - market wise listing 
		if(!empty($filter_arr['selected_market']) && strtolower($filter_arr['resourceType'])=='app'){
            //and parentID=0
            $qry =  "select 
            GROUP_CONCAT(id) as commodities
            from tbl_region_commodity_master where FIND_IN_SET('".$filter_arr['selected_market']."',f_market)  and itemtype='commodity' ";        
            $res = mysql_query($qry);
            $row = mysql_fetch_assoc($res);
            $market_commodities = $row['commodities'];
            $sql .= " AND (";
				$sql .= " commodityID IN (";
				$sql .=     $market_commodities;
				$sql .= ") OR ";
				$sql .= " subCommodityID IN (";
				$sql .=  $market_commodities;				
				$sql .= ") OR ";
				$sql .= " subsubCommodityID IN (";
				$sql .=   $market_commodities;
				$sql .= ")";
			$sql .= ")";
		}
		
		
		
		if(isset($filter_arr['regionID']) && !empty($filter_arr['regionID']) && !in_array("708", $filter_arr['regionID'])) {
			$regions = implode(",", $filter_arr['regionID']);
			$sql .= " AND ";
			$sql .= " (`regionID` IN (" . $regions;
				$sql .= ") OR `continentID` IN (" . $regions;
				$sql .= ")";
			$sql .= ")";
		
		}
		/*if(isset($filter_arr['company']) && !empty($filter_arr['company']))
		{
			$sql .= " AND for_smgroup_company like '%".$filter_arr['company']."%' ";		
		}*/
		$app_type = 'SM';
		/*if(!(isset($filter_arr['source']) && $filter_arr['source'] == 'newsLetter')){
			if(isset($filter_arr['app_type']) && !empty($filter_arr['app_type']))
			{
				$app_type = $filter_arr['app_type'];
				$web_domain = $app_type=='CM' ? "coalmint.com" : "steelmint.com";
				$sql .= " AND for_smgroup_company like '%".$web_domain."%' ";		
			} else {
				$sql .= " AND for_smgroup_company like '%steelmint.com%' ";	
			}
		}*/
		if(isset($filter_arr['searchTerms']) && !empty($filter_arr['searchTerms'])) {
			$cd = date("Y-m-d");
			$ct = date("H:i:s");
			mysql_query("
				insert into tbl_searches 
				values (
				'',
				'$cd',
				'$ct',
				$memid,
				'IntelInsight',
				'" . htmlspecialchars($filter_arr['searchTerms'], ENT_QUOTES) . "',
				''
				)"
			);
			$sql .= " AND (";

			$implode = array();

			$words = explode(' ', trim(preg_replace('/\s+/', ' ', $filter_arr['searchTerms'])));
			$words = str_replace(array("insight","insights", "news"), "", $words);
			$words =  preg_replace('/[^A-Za-z0-9\-]/', '', $words); // Removes special chars.
			foreach ($words as $word) {
					$implode[] = ' (`indexing` REGEXP "[[:<:]]' . $word . '[[:>:]]")   ';					
			}

			if ($implode) {
				$sql .= " " . implode(" AND ", $implode) . "";
			}

			$sql .= ")";
		}
		
        if(isset($filter_arr['renderAt']) && $filter_arr['renderAt'] == 'new_dashboard') {
            $limit = 10;
            if(isset($filter_arr['debug']) && $filter_arr['debug'] == 1) {
                echo "for_cnt:" . $sql . "<br />";
            }
            $rowsCnt = mysql_num_rows(mysql_query($sql));
            $pagesCntForDashboard = ceil($rowsCnt/$limit); 
            
        }

		$sidebar_tab='';
		$dtFrom='';
		$order_by = " ORDER BY post_created_date desc, post_created_time desc ";
		if(isset($filter_arr['featuredTab']) && !empty($filter_arr['featuredTab'])){
			$sidebar_tab = $filter_arr['featuredTab'];
			$limit=5;
			$order_by = " ORDER BY post_created_date desc, post_created_time desc ";
			switch(strtolower($sidebar_tab)){
					case 'most-read':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -15 days'));
						$order_by = "  ORDER BY most_read desc ";
					break;
					case 'top':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -7 days'));
						$order_by = "  ORDER BY most_read desc ";
					break;
					case 'editorial':
						//$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -2 days'));
						$sql .= " AND author_name=36 ";
					break;
			}
			if($dtFrom!='')
					$sql .= " AND post_created_date >= '$dtFrom' ";	
			
			///$sql .= $order_by. " LIMIT (int)$offset, " . (int)$limit;
			$sql .= $order_by. " LIMIT " . (int)$offset . ", " . (int)$limit;
			//filter to send the order in insight function
			$filter_insight['order'] =' desc ';
		}elseif(isset($filter_arr['API_Key']) && $filter_arr['API_Key']=='1dP9kOjmxZDt1'){
            if($filter_arr['API_from_date']!=''){
                $dtFrom = date('Y-m-d', strtotime($filter_arr['API_from_date'])).' 00:00:00';
                $sql .= " AND post_created_date >= '$dtFrom' ";	
            }
            if($filter_arr['API_to_date']!=''){
                $dtFrom =  date('Y-m-d', strtotime($filter_arr['API_to_date'])).' 23:59:59';
                $sql .= " AND post_created_date <= '$dtFrom' ";	
            }
            if($filter_arr['API_to_date']!='' && $filter_arr['API_from_date']!=''){                
                $str_diff = strtotime($filter_arr['API_to_date']) - (strtotime($filter_arr['API_from_date']));
                $dateDiff_inDays = floor($str_diff/3600/24);
               
                if($dateDiff_inDays>6){
                    return array();
                }
			}
            
            $sql .= " AND post_created_date >= '2019-09-01' ";	
            $sql .= " ORDER BY post_created_date desc, post_created_time desc ";
            
            $memid = 116707;
            
		}
		elseif(isset($filter_arr['source']) && $filter_arr['source'] == 'new_home'){
		    $limit=8;
		    ///$sql .= $order_by. " LIMIT (int)$offset, " . (int)$limit;
		    $sql .= $order_by." LIMIT " . (int)$offset . ", " . (int)$limit;
		}elseif(isset($filter_arr['source']) && $filter_arr['source'] == 'lohaacron'){
		    $limit=8;
		    ///$sql .= $order_by. " LIMIT (int)$offset, " . (int)$limit;
		    $dtFrom_cron = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -1 days'));
		    $sql .= " AND post_created_date = '$dtFrom_cron' ";	
		    $sql .= $order_by." LIMIT 0, 5";
		}
		elseif(strtolower($filter_arr['source']) == 'newsletter'){
			$sql .= " AND DATE(`post_created_date`) = '".date_yesterday()."'";
			$sql .= $order_by;
			///$sql .= $order_by. " LIMIT 0, 12";
		}elseif(isset($filter_arr['renderAt']) && $filter_arr['renderAt'] == 'new_dashboard') {
            $limit = 10;
		   /// $sql .= $order_by. " LIMIT (int)$offset, " . (int)$limit;
		    $sql .= $order_by. " LIMIT " . (int)$offset . ", " . (int)$limit;
        }else{
			//timeline filter added in 
			if(isset($filter_arr['timeLine']) || isset($filter_arr['timeline'])) {
				$dtFrom = $GLOBALS['currDate'];
				if( isset($filter_arr['timeLine']) )//coming in android
					$timeLine = $filter_arr['timeLine'];
				if( isset($filter_arr['timeline']) )//coming in ios
					$timeLine = $filter_arr['timeline'];
				switch(strtolower($timeLine)){
					case '1w':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -7 days'));
					break;
					case '2w':
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -14 days'));
					break;
					case '2d':
						//$sql .= " AND `post_created_date` > DATE_SUB(now(), INTERVAL 2 DAY)";
						$dtFrom = date('Y-m-d', strtotime($GLOBALS['currDate'] . ' -2 days'));
					break;
					}
					$sql .= " AND post_created_date >= '$dtFrom'";
			}
			if(isset($filter_arr['fromDate']) && $filter_arr['fromDate'] != ''){
				$dt = date('Y-m-d', strtotime($filter_arr['fromDate']));
				$sql .= " AND  `post_created_date` >= '$dt'";
			}
			
			if(isset($filter_arr['toDate']) && $filter_arr['toDate'] != '' && $filter_arr['toDate'] != 'tillDate'){
				$dt =  date('Y-m-d', strtotime($filter_arr['toDate']));
				$sql .= " AND  `post_created_date` <= '$dt'";
			}
			
			$limit = DEFAULT_NEWS_LIMIT;
			$sql .= " ORDER BY post_created_date desc, post_created_time desc ";
			$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		}
		//print_r($filter_arr);
		if(isset($filter_arr['debug']) && $filter_arr['debug'] == 1) {
    		print_r($filter_arr);
            echo "<br /><br /><pre>final sql:", $sql . ' -- ' . $offset . ' -- ' . $limit . ' -- ' . $memid . ' -- ' . $source;
        } 

		$res1=mysql_query($sql);
		
		$ids['intel']=array();
		$ids['insight']=array();
		if(mysql_num_rows($res1)>0){
			while($row=mysql_fetch_assoc($res1))
			{
				$ids[$row['f_section']][] = $row['post_id'];
			}
		}else{
			return $result;
		}
		
		if(isset($filter_arr['debug']) && $filter_arr['debug'] == 1) {
		    echo "<pre>";
		    print_r($ids);
		}
		
		
		$filter_intel["post_id"] = empty($ids['intel'])?array(0):$ids['intel'];
		if(isset($filter_arr['featuredTab']) && !empty($filter_arr['featuredTab']) && ($filter_arr['featuredTab']=='top' || $filter_arr['featuredTab']=='most-read'  ) )
			$filter_intel["orderBy"] = ' most_read ';
		else
			$filter_intel["orderBy"] = 'datePublished';
		$filter_intel["dontShowAd"] = 'Y';
		$resourceType='app';
		
		$filter_intel["API_Key"] =  $filter_arr["API_Key"];
		$filter_intel["selected_market"] = $filter_arr['selected_market'];
		if(isset($filter_arr['resourceType']) && $filter_arr['resourceType']!='')
            $resourceType = $filter_arr['resourceType'];
        
         $filter_intel["debug"] =  $filter_arr["debug"];
	    if( $memid != '' ){
	           // $filter_intel["source"] = "portfolio";
	    $filter_intel["sourceNew"] = $filter_arr['source'];
            $result_intel = self::getIntelRowSet($memid,$resourceType,'',$filter_intel,'post',count($ids['intel']),0,$app_type);
	        
        } else
            $result_intel = self::getIntelRowSet(0,$resourceType,'',$filter_intel,'pre',count($ids['intel']),0,$app_type);
            
        $filter_insight["itemID"] = empty($ids['insight'])?array(0):$ids['insight'];
        if(isset($filter_arr['featuredTab']) && !empty($filter_arr['featuredTab']) && ($filter_arr['featuredTab']=='top' || $filter_arr['featuredTab']=='most-read'  ) ){
			$filter_insight["sort"] = 'n.`most_read`';
			
		}
        else        
			$filter_insight["sort"] = 'n.`created_at`';
        $filter_insight["API_Key"] =  $filter_arr["API_Key"];
        $filter_insight["debug"] =  $filter_arr["debug"];
        $filter_insight["selected_market"] = $filter_arr['selected_market'];
        $source ='listing';
        if(isset($filter_arr['source']) && ($filter_arr['source'] == 'portfolio'))
            $source =$filter_arr['source'];
        if( $memid != '' ){
	       // if(isset($filter_arr['renderAt']) && $filter_arr['renderAt'] == 'new_dashboard')
	         //   $filter_insight["source"] = "portfolio";
            $filter_insight["sourceNew"] = $filter_arr['source'];    
            $result_insight = self::getInsightsRows($memid,$source,$resourceType,'default',$filter_insight,'post',count($ids['insight']),0,$app_type);
        } else
            $result_insight = self::getInsightsRows(0,$source,$resourceType,'default',$filter_insight,'pre',count($ids['insight']),0,$app_type);

        if(isset($filter_arr['debug']) && $filter_arr['debug'] == 13) {
            echo "<pre>";
            print_r($result_intel);
            //print_r($result_insight);
        }



        $sort_by_noOfReads =array();
        foreach($result_intel["Intels"] as $k=>$v){
          $time = strtotime($v['datePublished']);
          
          //sometimes datePublished of mutliple intels/insights are same and so it affects the resultset count. so we are incrementing the time by 1 if same time value is found in the array
          if( isset($sorted[$time]) )
            $time += 1;
            
          if(isset($filter_arr['debug']) && $filter_arr['debug'] == 13)
            echo "<br /> time:" . $time . '--' . $v['itemID'];
          //if( 8598 == $v['itemID'] )    
            //echo "<br /> time:" . $time;
          
		  $v['thumbnailType'] = $v['type'];
		  $v['mainImageURL'] = $v['imageUrl'];
		  $v['videoURL'] = $v['videoUrl'];
		  $v['intelOrInsight'] = "Intel";

		  unset($v['type']);unset($v['imageUrl']);unset($v['videoUrl']);
          $sorted[$time]= $v; 
          if($sidebar_tab=='top' || $sidebar_tab=='most-read')
				$sort_by_noOfReads['noOfReads'][$time] = $v['noOfReads'];
        }
        
        foreach($result_insight as $k=>$v){
           	$time = strtotime($v['datePublished']);

          //sometimes datePublished of mutliple intels/insights are same and so it affects the resultset count. so we are incrementing the time by 1 if same time value is found in the array
	        if( isset($sorted[$time]) )
                $time += 1;
//echo "<br /> time1:" . $time;
           	if(isset($filter_arr['debug']) && $filter_arr['debug'] == 13)
           	    echo "<br /> time1:" . $time;
            $v['intelOrInsight'] = "Insight";
            $sorted[$time] = $v;   
            if($sidebar_tab=='top' || $sidebar_tab=='most-read')
				$sort_by_noOfReads['noOfReads'][$time] = $v['noOfReads'];
        }
        
        if(isset($filter_arr['debug']) && $filter_arr['debug'] == 134) {
            echo "<pre>";
            print_r($sorted);
        }
        
        if($sidebar_tab=='top' || $sidebar_tab=='most-read')
			array_multisort($sort_by_noOfReads['noOfReads'], SORT_DESC,$sorted);
		else
			krsort($sorted,SORT_NUMERIC); 
        
        $count=0;
        foreach($sorted as $k=>$v){
            $result[] = $v;
            $count++;
        } 

        if(isset($filter_arr['renderAt']) && $filter_arr['renderAt'] == 'new_dashboard') {
            $finres = array();
            $finres["dataValue"] = $result;
            $finres["cntValue"] = $pagesCntForDashboard;
            
            return $finres;
        } else {
            return $result;
        }

        
        //return $result;
	}
	
	
	function get_read_time($content){
		if($content!=''){
			$stripped = strip_tags($content);
			$decoded  = html_entity_decode($stripped);
			$wrd_count = str_word_count($decoded);	
			$min_val  = round($wrd_count/60);
			return $min_val." Min";
		}
	}
	
	function create_json_for_region(){
		$region_qry = " select itemName,id from tbl_region_commodity_master where itemType='region' ";
		$region_res = mysql_query($region_qry);
		$region_arr = array();
		while($region_row= mysql_fetch_assoc($region_res))
		{
			$region_arr[$region_row['id']]=$region_row['itemName'];
		}
		/*
		$for_intel_insight='all_commodity_wise';
		$for_comm='all';
		
		$query  = "select distinct commodityID,regionID,continentID from intel where regionID!=0 and continentID!=0 and commodityID!=0  ";
		$res = mysql_query($query);
		$for='intel';
		
		while($row =mysql_fetch_assoc($res)){
			$data[$for][$row['continentID']]['id'] =$row['continentID'];
			$data[$for][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
			
			$data[$for_comm][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_comm][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_comm][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);		
			
			$data[$for_intel_insight][$row['commodityID']][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_intel_insight][$row['commodityID']][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_intel_insight][$row['commodityID']][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
			
		}	
		$for='insights';
		$query  = "select distinct commodityID,regionID,continentID from tbl_news_post where regionID!=0 and continentID!=0 and commodityID!=0  ";
		$res = mysql_query($query);
		while($row =mysql_fetch_assoc($res)){
			$data[$for][$row['continentID']]['id'] =$row['continentID'];
			$data[$for][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
			
			$data[$for_comm][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_comm][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_comm][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);		
			
			$data[$for_intel_insight][$row['commodityID']][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_intel_insight][$row['commodityID']][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_intel_insight][$row['commodityID']][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
		}
		
		//for coalmint
		$for_intel_insight='all_commodity_wise_CM';
		$for_comm='all_CM';
		
		$query  = "select distinct subCommodityID,regionID,continentID from intel where regionID!=0 and continentID!=0 and subCommodityID!=0 and subCommodityID!=0 and   commodityID=401";
		$res = mysql_query($query);
		$for='intel_CM';
		
		while($row =mysql_fetch_assoc($res)){
			$data[$for][$row['continentID']]['id'] =$row['continentID'];
			$data[$for][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
			
			$data[$for_comm][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_comm][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_comm][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);		
			
			$data[$for_intel_insight][$row['subCommodityID']][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_intel_insight][$row['subCommodityID']][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_intel_insight][$row['subCommodityID']][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
			
		}	
		$for='insights_CM';
		$query  = "select distinct subCommodityId,regionID,continentID from tbl_news_post where regionID!=0 and continentID!=0 and subCommodityId!=0 and subCommodityId!=0  and commodityID=401";
		$res = mysql_query($query);
		while($row =mysql_fetch_assoc($res)){
			$data[$for][$row['continentID']]['id'] =$row['continentID'];
			$data[$for][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
			
			$data[$for_comm][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_comm][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_comm][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);		
			
			$data[$for_intel_insight][$row['subCommodityId']][$row['continentID']]['id'] =$row['continentID'];
			$data[$for_intel_insight][$row['subCommodityId']][$row['continentID']]['name'] =$region_arr[$row['continentID']];
			$data[$for_intel_insight][$row['subCommodityId']][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
		}*/  
      
        $mkt_arr = array(
            "ferrous"=> array("id"=>"408, 410, 413, 403, 412, 980, 407,402,415,416,417,431","level_key"=>"commodityID"),
            "non-ferrous"=> array("id"=>"972","level_key"=>"subCommodityId"),
            "coal"=> array("id"=>"401,407","level_key"=>"subCommodityId"),
            "scrap-recycling"=> array("id"=>"439,440,442,973,996,997,445,981","level_key"=>"commodityID"),
        );
        foreach($mkt_arr as $key=>$val){
            $mkt  = $val['id'];
            $level_key  = $val['level_key'];
            $for_intel_insight=$key.'-all_commodity_wise';
            $for_comm=$key.'-all';
            
            $query  = "select distinct $level_key,regionID,continentID from intel where regionID!=0 and continentID!=0 and commodityID!=0 and 
            (
                commodityID in ($mkt) OR
                subCommodityID in ($mkt) OR
                subSubCommodityID in ($mkt)
            )
            ";
            $res = mysql_query($query);
            $for=$key.'-intel';
            
            while($row =mysql_fetch_assoc($res)){
                $data[$for][$row['continentID']]['id'] =$row['continentID'];
                $data[$for][$row['continentID']]['name'] =$region_arr[$row['continentID']];
                $data[$for][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
                
                $data[$for_comm][$row['continentID']]['id'] =$row['continentID'];
                $data[$for_comm][$row['continentID']]['name'] =$region_arr[$row['continentID']];
                $data[$for_comm][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);		
                
                $data[$for_intel_insight][$row[$level_key]][$row['continentID']]['id'] =$row['continentID'];
                $data[$for_intel_insight][$row[$level_key]][$row['continentID']]['name'] =$region_arr[$row['continentID']];
                $data[$for_intel_insight][$row[$level_key]][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
                
            }	
            $for=$key.'-insights';
            $query  = "select distinct $level_key,regionID,continentID from tbl_news_post where regionID!=0 and continentID!=0 and commodityID!=0  and 
            (
                commodityID in ($mkt) OR
                subCommodityID in ($mkt) OR
                subSubCommodityID in ($mkt)
            )
            ";
            $res = mysql_query($query);
            while($row =mysql_fetch_assoc($res)){
                $data[$for][$row['continentID']]['id'] =$row['continentID'];
                $data[$for][$row['continentID']]['name'] =$region_arr[$row['continentID']];
                $data[$for][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
                
                $data[$for_comm][$row['continentID']]['id'] =$row['continentID'];
                $data[$for_comm][$row['continentID']]['name'] =$region_arr[$row['continentID']];
                $data[$for_comm][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);		
                
                $data[$for_intel_insight][$row[$level_key]][$row['continentID']]['id'] =$row['continentID'];
                $data[$for_intel_insight][$row[$level_key]][$row['continentID']]['name'] =$region_arr[$row['continentID']];
                $data[$for_intel_insight][$row[$level_key]][$row['continentID']]['region'][$row['regionID']] =array('id'=>$row['regionID'],'name'=>$region_arr[$row['regionID']]);
            }
		}
		$json = json_encode(array('data' => $data));
		
		//write json to file
		$file_name = '/home/steelmin/public_html/api_bm/pre_function/intel_insight.json';
		file_put_contents($file_name, $json);
	}
	
	
    function get_data_collection_participants($asst_id=0,$col_date=''){
        $result=array();$collected_by_arr=array();$data=array();
            if(!empty($asst_id) && $col_date!=''){
                /*if($col_date!='')
                    $col_date = date("Y-m-d",strtotime($col_date));
                else
                    $col_date = date("Y-m-d");*/
            $col_date = date("Y-m-d",strtotime($col_date));
            $today_date =  date("Y-m-d");
            if(strtotime($today_date) >= strtotime($col_date)){
                $qry =  "select collected_from_pp,price_type,normalized_price,quantity,time_of_call,outlier,pid from tbl_data_collection_new where pid=$asst_id and p_flag='A' and f_date='".$col_date."' and price_type<>'OTHERS' and outlier<>''  order by time_of_call asc,id asc ";
            
                $res = mysql_query($qry);            
                while($row = mysql_fetch_assoc($res)){
                    $row['normalized_price'] =  showDataInNumberFormat($row['normalized_price']);
                    //$row['quantity'] =  showDataInNumberFormat($row['quantity']);             
					$row['quantity'] =  $row['quantity'];
                    $data[] = $row;
                    $collected_by_arr[] = $row['collected_from_pp'];                    
                }                 
                //print_r($data);
                /* $collected_by_list = array();
                if(!empty($collected_by_arr)){
                    $collected_by_arr = array_unique($collected_by_arr);
                    foreach($collected_by_arr as $key=>$val){
                        $key1 = "P".($key + 1);
                        $collected_by_list[$val] = $key1;
                    }
                    
                }*/            
                $result['status']=1001;
                $result['data']['rows'] = $data;
                $result['data']['collection_date'] = $col_date;
            }else{
                $result['status']=2100;
                $result['data'] = array();
                $result['message']="Not allowed to access price after today's date";
            }
        }
        else{
            $result['status']=2100;
            $result['data'] = array();
            $result['message']="Assesment/Date not selected to fetch price.";
        }
        return $result;
    }
    
     public static function getPriceSpreadRows($memid=0, $source='listing', $resourceType="app", $type='default', $filter=array(), $pageType='post', $limit=5, $offset=0, $appType='SM', $_currency=''){
		//include_once "/home/steelmin/public_html/inc/config1.php"; 
        $result=array(); 
        $prices = array();
        $pricesT = array();
		
		$f_order_by_col='id';
		if($appType=='CM')
			$f_order_by_col='id';
		
			
		$f_cnf_fob='f';$table = 'tbl_spread_master';   
		
		$sql = "SELECT m.`id`,";		
		$sql .= "	case when m.frequency='weekly' then 'W'
                        when m.frequency='monthly' then 'M'
                        else 'D' end as assessment, 
		            m.frequency AS `assessmentText`, 			
					m.`spread_update_day` AS `publication_day_time`,
					n.`price_diff` AS price,
					n.`1W`,
					n.`1M`,
					n.`3M`,					
					n.f_datetime as `date_time_formatted`,
					m.`spread_update_day` as publicationDayTime,
					'f' as f_cnf_fob,
					'INR' as currency,
					'IN' as flag,
					m.`$f_order_by_col`";

		$sql .= " , m.regionID , m.countryID";
		
		
		
          $sql .= " ,(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = m.commodityID) as commodityName ";
		  $sql .= " ,(SELECT `itemName` FROM `tbl_region_commodity_master` WHERE `itemType` = 'commodity' and `ID` = m.subCommodityID) as subCommodityName "; 
			$sql .= " ,(select itemName from tbl_region_commodity_master as cm where m.countryID=cm.id and itemType='region') as regionName ";
		  
		
		$sql .= " ,m.commodityID, m.SubCommodityID";
		$sql .= " , m.parentID, m.spread_name as title";
		/* n.`lat_long`, */
//

		if($memid) {
			$sql .= ", (SELECT COUNT(up.`id`) FROM `tbl_user_portfolio` up WHERE up.`user_id` = '" . $memid . "' AND up.`row_id` = m.`id` AND up.`type` = 'price_spread' and 'f'=up.`prices_col`) as portfolio";
			//$sql .= ",(select id from tbl_alerts as c where c.x_days_before=n.`f_cnf_fob` and m.id=c.item_id and memid=$memid and section='price' and status='active'  limit 1) as isSetAlert";
			$sql .= ", '' as isSetAlert ";
		} else {
			$sql .= ", 0 as portfolio, '' as isSetAlert";
		}
		
	
		
		$sql .= " FROM `" . $table . "` m";
		$sql .= " JOIN `tbl_spread_prices` n ON m.`id` = n.`spread_mst_id`";	

		$sql .= " WHERE m.`id` > 0 and  m.parentID=0 ";

		$orderBY = "case 
							when commodityName='Iron Ore' then 1
							when commodityName='Coal' then 2
							when commodityName='Scrap & Metallics' then 3
							when commodityName='Steel' then 4
							when commodityName='Ferro Alloy' then 5
							when commodityName='Ship Breaking' then 6
							else 99
						end,
						case 
							when subCommodityName='Semi Finished' and zone = 'NORTH INDIA' then 1
							when subCommodityName='Semi Finished' and zone = 'EAST INDIA' then 2
							when subCommodityName='Semi Finished' and zone = 'CENTRAL INDIA' then 3
							when subCommodityName='Semi Finished' and zone = 'WEST INDIA' then 4
							when subCommodityName='Semi Finished' and zone = 'SOUTH INDIA' then 5
							else 99
						end";
		
		$chkSource = true;
		
		if($source=='details'){
			$chkSource = false;
			$_source=$source;
			$source='';
			$orderBY = "";
		}
		$actualSource = $source;
		if($source!='') {//source
			
			switch($source){				
				case 'indiaPrice':
				case 'indiaprice':
					$source= '';	
					$chkSource = false;
				break;
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark'://no bookmark for prices

					$chkSource = false;
				break;
				case 'portfolio':
                    if(isset($filter['download']) &&  $filter['download']!='y'){
						$portfolio['f'] = $filter['download'];
						$portfolio['cnf'] = array(0);
						$portfolio['fob'] =  array(0);
						$filter['download']='y';
					}else{
						$common = new Common();
						$portfolio = $common->getUserPortfolioV2019($memid, 'prices', $appType);

						if(empty($portfolio)){
							$portfolio['f'] = array(0);
							$portfolio['cnf'] = array(0);
							$portfolio['fob'] = array(0);
						}						 
					}
					$filter['itemID'] = $portfolio;
					$source= '';
					$chkSource = false;
				break;
				case 'relatedPrices':
				case 'relatedprices':
					//relatedSection
					//relatedItemID
					//"relatedItemID":119687,"relatedSection":"insight"
					$filter['commodityID'] = array(426); 
					$source= '';
					$chkSource = false;
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'keyindex':
				case 'watchlist':
					///$filter['commodityID'] = array(448); 
					///$source= '';
					$chkSource = false; 
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'recommendedPrices':
				case 'recommendedprices':
					$common = new Common();
					$cr_data = $common->getUserPortfolioV2019($memid, 'intel_insight', $appType);
					if(empty($cr_data)){
						$source= 'home';
					}else{
						$filter['commodityID'] = array(); 
						$filter['regionID'] = array();
						
						foreach($cr_data as $K=>$v){
								array_push($filter['commodityID'],$v["commodityId"]);
								array_push($filter['regionID'],$v["regionId"]);
						}
						$source= '';						
					}
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'alerts':
				case 'alert':
                 	$common = new Common();
					$alerts = $common->getUserAlertsV2019($resourceType, $memid, $type='price');

					if(empty($alerts)){
						$alerts['f'] = array(0);
						$alerts['cnf'] = array(0);
						$alerts['fob'] = array(0);
					}
					$filter['itemID'] = $alerts; 
					$source= '';
					$chkSource = false;
				break;
				case 'commodity':
				case 'commoditywise':
					$orderBY .= " ,commodityID, SubCommodityID, regionID ";
				break;
				case 'region':
				case 'regionwise':					
					if($orderBY)
						$orderBY .= " ,regionID, commodityID, SubCommodityID ";
					else
						$orderBY .= " regionID, commodityID, SubCommodityID ";
				break;
				default: //like listing , mapview and others					
					if(isset($filter['itemIdPriceType'])):
						$itemIdPriceType = array();
						foreach($filter['itemIdPriceType'] as $itmPT):
							list($_rid, $_rtype) = explode('_', $itmPT);
							$itemIdPriceType[$_rtype][] = $_rid;
						endforeach;

						if(empty($itemIdPriceType)){
							$portfolio['f'] = array(0);
							$portfolio['cnf'] = array(0);
							$portfolio['fob'] = array(0);
						}
						$filter['itemID'] = $itemIdPriceType; 
						$source= '';
						$chkSource = false;
					endif;
				
					if($orderBY)
						$orderBY .= " ,parentID, f_datetime Desc ";
					else
						$orderBY = " ,parentID, f_datetime Desc ";
				break;
			}
		}		
		
		if(isset($filter['fromdate']) && $filter['fromdate'] != '') {
			$sql .= " AND DATE(f_date) >= '" . $filter['fromdate'] . "'";
			$sql .= " AND DATE(f_date) <= '" . $filter['todate'] . "'";
			
		}
		
		if(isset($filter['itemID']) && !empty($filter['itemID'])) {
			
			if(is_array($filter['itemID'])){
				$whereRowIds = array();
			
				foreach($filter['itemID'] as $_cnf_fob=>$row_ids) {
					$whereRowIds[] = "(n.`spread_mst_id` IN (" . implode(", ", $row_ids) . "))";
				}
				$sql .= " AND (";
				$sql .= implode(" OR ", $whereRowIds);
				$sql .= ")";
				
			}else{//for detail page
					$sql .= " AND (n.`spread_mst_id` = " . (int)$filter['itemID']." )";					
			}
		}
		
		//for 'recommendedprices'
		if(isset($cr_data) && $source==''){
			$sql .= " AND (";
			if(isset($filter['commodityID']) && !empty($filter['commodityID'])  && !in_array("709", $filter['commodityID'])) {
				
					$sql .= " n.`subCommodityID` IN (";
					$sql .= implode(", ", $filter['commodityID']);
					$sql .= ")";				
			}
			
			if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
				$regions = implode(",", $filter['regionID']); 	
				$sql .= " OR ";	
					$sql .= " m.`countryID` IN (" . $regions;
					$sql .= ")";
			}
			
			$sql .= ")";
		}
		else{//
			if(isset($filter['commodityID']) && !empty($filter['commodityID']) && !in_array("709", $filter['commodityID'])) {
				$sql .= " AND (";
					$sql .= " m.`commodityID` IN (";
					$sql .= implode(", ", $filter['commodityID']);
					$sql .= ")";
				$sql .= " OR ";	
					$sql .= " m.`subCommodityID` IN (";
					$sql .= implode(", ", $filter['commodityID']);
					$sql .= ")";				
				$sql .= ")";
			}		
			
			if(isset($filter['regionID']) && !empty($filter['regionID']) && !in_array("708", $filter['regionID'])) {
                $regions = implode(",", $filter['regionID']); 	
				$sql .= " AND (m.`countryID` IN (" . $regions;
							$sql .= ") or m.`regionID` IN (" . $regions;
							$sql .= ") )";
			}
		}	

        
		//check if any steelmint user is logged in. if yes, show him the futures prices
		$isSteelMintUserLoggedIn = 0;
		if( $memid != 0 && $memid != '' ) {
			$usernameOfMemid = qryToCommaSepString("select concat(username,',',email,',',addtnl_email) from tbl_members where id = $memid and id <> 116707"); //chk for all records except for memid = 116707 which is anmol_platinum@steelmint.com
			if( strpos( $usernameOfMemid, "steelmint.com" ) !== false || strpos( $usernameOfMemid, "steelmintgroup.com" ) !== false ){
				$isSteelMintUserLoggedIn = 1;
			}
		}

        if(isset($filter['debug']) && $filter['debug'] == 1) {
				echo "<br /> appType:" . $appType;
				echo "<br /> isSteelMintUserLoggedIn:" . $isSteelMintUserLoggedIn;
				echo "<br /> memid:" . $memid;
				print_r($filter);
				
		}
		
		$sqlTC = "select distinct currency_code, currency_symbol 
				from tbl_country
                where  section like 'price%'
                order by country
            ";
		$rsTC = mysql_query($sqlTC)or die(mysql_error().$sqlTC);
		$symbolType['CEN'] = 'FFE0';
		while($rowTC = mysql_fetch_assoc($rsTC)){
			$symbolType[$rowTC['currency_code']] = $rowTC['currency_symbol'];
		} 
        $orderBY=" $f_order_by_col, parentID ";
		if(isset($filter['price_section_type']) && !empty($filter['price_section_type']) && $resourceType=='web'){
			/* $orderBY = " regionID,commodityID, SubCommodityID,$f_order_by_col "; */
			$_con1="";
			if(isset($filter['commodityID'])){				
				$_con1=" and (subCommodityID in (".implode(", ", $filter['commodityID'])." ) OR subSubCommodityID in (".implode(", ", $filter['commodityID'])." ))";
			}
			if(isset($filter['regionID'])){				
				$_con1.=" and regionID in (".implode(", ", $filter['regionID'])." )";
			}
			/*$f_order_by_countryID = qryToCommaSepString("SELECT n.countryID FROM `tbl_prices_sequence` as ps
								left join tbl_price_static as n ON n.relation_id=ps.relation_id
								where continue_or_discontinue=1  $_con1
								group by regionID, countryID
								order by ps.f_order_by, ps.id");*/
								
			$orderBY = " case 
							when commodityName='Iron Ore' then 1
							when commodityName='Coal' then 2
							when commodityName='Scrap & Metallics' then 3
							when commodityName='Steel' then 4
							when commodityName='Ferro Alloy' then 5
							when commodityName='Ship Breaking' then 6
							else 99
						end,
						 ";///FIELD(psRegionID, $f_order_by_regionID),
			/*if($f_order_by_countryID){
				$orderBY .=" commodityID, SubCommodityID,FIELD(countryID, $f_order_by_countryID), $f_order_by_col, parentID,
						`date_time_formatted` Desc";
			}else*/{
				$orderBY .=" commodityID, SubCommodityID, $f_order_by_col, parentID,
						`f_datetime` Desc";
			}			
		}
		
		if($resourceType=='web' && strtolower($source)=='commoditywise' && !empty($filter['commodityID']) && implode(", ", $filter['commodityID']) == 410){
			$sql .= " ORDER BY 
						case 
							when subCommodityName='Sponge Iron' then 1
							when subCommodityName='Pig Iron' then 2
							when subCommodityName='Melting Scrap' then 3
							when subCommodityName='Rerolling scrap' then 4
							when subCommodityName='Mill Scale' then 5
							else 99
						end, $f_order_by_col, parentID,
						`f_datetime` Desc";		
		}elseif (isset($filter['sort']) && in_array($filter['sort'], $sort_data)) {
			$sql .= " ORDER BY " . $filter['sort'];
			if(isset($filter['order']))
				$sql .= " " . $filter['order'];
		}elseif($orderBY!=''){
			$sql .= " ORDER BY 
						
						" . $orderBY;
		}elseif($_source!='details'){
			
			$sql .= " ORDER BY 
						case 
							when commodityName='Iron Ore' then 1
							when commodityName='Coal' then 2
							when commodityName='Scrap & Metallics' then 3
							when commodityName='Steel' then 4
							when commodityName='Ferro Alloy' then 5
							when commodityName='Ship Breaking' then 6
							else 99
						end,
						case 
							when subCommodityName='Semi Finished' and zone = 'NORTH INDIA' then 1
							when subCommodityName='Semi Finished' and zone = 'EAST INDIA' then 2
							when subCommodityName='Semi Finished' and zone = 'CENTRAL INDIA' then 3
							when subCommodityName='Semi Finished' and zone = 'WEST INDIA' then 4
							when subCommodityName='Semi Finished' and zone = 'SOUTH INDIA' then 5
							else 99
						end,
						`f_datetime` Desc";
		}

        $rowsCnt = 0;
        //if APi called from new dashborad on steelmint site and its the 1st page then send count of total records.
        //if APi called from new dashborad on steelmint site then send 10 records
        if(isset($filter['renderAt']) && $filter['renderAt'] == 'new_dashboard') {
            $limit = 10;
            $rowsCnt = mysql_num_rows(mysql_query($sql));
            $pagesCntForDashboard = ceil($rowsCnt/$limit);  
        }elseif(isset($filter['price_section_type']) ){
			if( isset($filter['deviceType']) && $filter['deviceType'] == 'ios')
				$limit = 8;
			elseif($resourceType=='web')
				$limit = 3000;
			else
				$limit = 11;
		}elseif(isset($cr_data))
		    $limit = RECOMMENDED_LIMIT;
		elseif($source=='home')
			$limit = DEFAULT_LIMIT_HOME;
		elseif($resourceType=='web' && (strtolower($source)=='commoditywise' || strtolower($source)=='regionwise'))
			$limit = 3000;
		elseif(isset($filter['download']) && $filter['download']=='y')
			$limit = 3000;
		/* elseif($source=='keyindex' || $source=='watchlist') 
			$limit = KEYPRICES_LIMIT;*/
		else 
			$limit = DEFAULT_PRICES_LIMIT;
			//$limit = DEFAULT_LIMIT;
		
		if(isset($filter['fromdate']) && $filter['fromdate'] != '') {
			//if its for customized case then dont apply any limit. send all data
		}elseif(!$chkSource){
			$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		}elseif(strtolower($source)!='mapview'){
			$sqlIds = $sql;
			$sqlIds .= " LIMIT " . (int)$offset . ", " . (int)$limit;
			
 			if(isset($filter['debug']) && $filter['debug'] == 1) {
				echo "sqlIds:" . $sqlIds . "<br />";
			}		
			
			$parenIDS='0';
			$parenIDSQry = qryToCommaSepString($sqlIds);
		//	if(isset($filter['debug']) && $filter['debug'] == 1) {
			//	echo "<br /> parenIDSQry:" . $sqlIds . "<br />";
		//	}
 			if($parenIDSQry=='')
				$parenIDSQry = -1;
			$CparenIDSQry = qryToCommaSepString("select id from tbl_spread_master where parentID in ($parenIDSQry)");
			if($parenIDSQry){
				if($CparenIDSQry)
					$parenIDSQry.=','.$CparenIDSQry;
				$addCond = " AND (m.`id` IN($parenIDSQry)) ";
				$sql = str_replace("m.`id` > 0", "m.`id` > 0 " . $addCond , $sql);
			}else{
				///echo 'NA';
			}
		}

		
		$query = mysql_query($sql);
		if(isset($filter['debug']) && $filter['debug'] == 1) {
			echo "count: " . mysql_num_rows($query);
			echo "<br /> sql:" . $sql . "<br />";
		}	
		$region='';$regionCnt = 0;
		$viewMore = array();
		$result = array();
		$prices = array();
		$assessments = [
			'D'	=>	'Daily',
			'W'	=>	'Weekly',
			'M'	=>	'Monthly',
			'BW'	=>	'Biweekly'
		];	
		
		$mapp = '';
        if(isset($filter['mapp_css']) && $filter['mapp_css'] != '') {
            /*if( $memid == 56350 )
                $mapp = file_get_contents("https://www.theitbooth.com/nw/storage/cssEnc/" . $filter['mapp_css'] . ".json");
            else    */
                $mapp = file_get_contents(config('constants.siteUrl') . "storage/cssEnc/" . $filter['mapp_css'] . ".json");
            $mapp = json_decode($mapp,true);
			
		}		
        /*if( $memid == 56350 ){		
            echo "https://theitbooth.com/nw/storage/cssEnc/" . $filter['mapp_css'] . ".json";
            echo "<pre>";
            print_r($mapp);
        }*/
        

		
		while($row = mysql_fetch_assoc($query)){			
			$sectionHeading='';
			$subSectionHeading='';
			if(strtolower($source)=='commodity' || strtolower($source)=='commoditywise' || (isset($filter['tabFilter']) || $filter['tabFilter']=='home') || (isset($filter['price_section_type']) && $resourceType=='web')){
				/* $sectionHeading = $row['category'];
				$subSectionHeading = $row['sub_category']; */
				if($row['regionID'])
					$sectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='commodity' and ID=".$row['SubCommodityID']);
				if($row['regionID'])
					$subSectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['regionID']);
			}elseif(strtolower($source)=='region' || strtolower($source)=='regionwise' ){
				if($row['regionID'])
					$sectionHeading  = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['regionID']);
				if($row['SubCommodityID'])
					$subSectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='commodity' and ID=".$row['SubCommodityID']);
				/* if($row['parentRegionID'])
					$sectionHeading  = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['parentRegionID']);
				if($row['regionID'])
					$subSectionHeading = qryToCommaSepString("SELECT itemName FROM `tbl_region_commodity_master` where itemType='region' and ID=".$row['SubCommodityID ']); */
			}

			$flag=$row['flag']!=''?strtolower($row['flag']):'noflag';
			$result['itemID'] = intval($row['id']);			
			$result["sectionHeading"] = utf8_decode($sectionHeading);
			$result["subSectionHeading"] = utf8_decode($subSectionHeading);
			$result["flagUrl"] = "https://www.steelmint.com/steeladmin/flags/".$flag.".png";
			//$result["title"]= $row['sticky_header_value'].' : '.$row['particular'];
			$result["title"]= $row['title'];
			//$hrf = BASEURL."price/".url_title($row['title'].'-'.$row['id'],$separator = '-', $lowercase = true);
			$hrf = BASEURL."spread/detail/".url_title($row['title'].'-'.$row['id'].'-INR',$separator = '-', $lowercase = true);
			$datePublishedIN='IST';;
			$result["href"]=$hrf;
			
			$result["compareTitle"]= utf8_decode($row['title']);
			$result["compareSubTitle"]= '';
			
			///$result["datePublished"]= date('Y-m-d H:i:s', strtotime($row['date_time']));
			$result["datePublished"]=  date('Y-m-d H:i:s', strtotime($row['date_time_formatted']));
			$result["datePublishedIN"]= $datePublishedIN;
			$result["regionID"] = intval($row['regionID']);
			$result["regionName"] = is_null($row['regionName'])?'Others':$row['regionName'];
			$result["commodityID"] = intval($row['SubCommodityID']);
			$result["commodityName"] = utf8_decode($row['commodityName']);
			$result["subCommodityName"] = utf8_decode($row['subCommodityName']);
			
			$result["assessment"]= isset($assessments[$row['assessment']]) ? $assessments[$row['assessment']] : '';
			$f_cnf_fob= $row['f_cnf_fob'];
			$result["assessmentText"]=	isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment'];
			$result["isBookmarked"] = "n";
			$result["isAddedToPortfolio"] = $row['portfolio']!=0?'y':'n';
			$result["isSetAlert"] = $row['isSetAlert']!=''?'y':'n';
			$_currencyName = $row['currency'];
			
			$currencySymbol = isset($symbolType[$_currency])?$symbolType[$_currency]:$symbolType[$_currencyName];	
			
			$_currencyName = $_currency!=''?$_currency:$_currencyName;			
			if($resourceType=='web' &&  $currencySymbol!='')
				$currencySymbol=  str_replace(",",";&#x", $currencySymbol).';';
			$result["currency"] = 
						array(
						  "symbol" => !empty($currencySymbol)?$currencySymbol:"",//"₹"
						  "name" => !empty($_currencyName)?$_currencyName:""
						);
			/* $result["currency"] = 
						array(
						  "symbol" => "U+00A2",//"₹"
						  "name" => "&#x00a2;"
						); */	
	
			$result["price"]= $pageType=='pre'?'hidden': trim(strip_tags($row['price']), 	$currencySymbolDefault);
			
			
			$mprice = str_replace(",","",$result["price"]);
			$isDoubleVal = false;
			$currencyConvertor=1;
			if($result["price"]!='' && $result["price"]!='NA' && $pageType=='post'){
				$result["price"] = str_replace(",","",$result["price"]);
				//if(is_double($result["price"])){
				if ( strpos( $result["price"], "." ) !== false ){
					if(intval($result["price"])<2)
					$result["price"] = number_format(str_replace(",","",$result["price"])*$currencyConvertor,4);
					else
					$result["price"] = number_format(str_replace(",","",$result["price"])*$currencyConvertor,2);
					
					$isDoubleVal = true;
				}else{
					$result["price"] = number_format($result["price"]*$currencyConvertor);
				}
			}
			//$result["price"] = (string)$result["price"].$perUnit;
			$result["price"] = (string)$result["price"];
			$result["priceType"] = utf8_decode($f_cnf_fob);
			if($f_cnf_fob=='f')
				$tradeType = 'Domestic';
			
			
			$show_intraday='';
			if(( intval($row['SubCommodityID'])==443 ||  intval($row['SubCommodityID'])==439 ||  intval($row['subSubCommodityID'])==471 ) &&  utf8_decode($f_cnf_fob)=='f')
			{
				$show_intraday='Y';	
			}
			$result["showIntraDay"] = $show_intraday;
			$result["dataSource"] = $row['commodityID']==401?'CoalMint':'SteelMint';
			$result["tradeType"] = utf8_decode($tradeType);
			$result["tradeType3Chars"] = strtoupper(substr(utf8_decode($tradeType), 0, 3));
			///$result["delayed"] = trim(preg_replace("/\r|\n/", "", $row['remark']));
			$result["delayed"] = '';//strpos( strtolower($row['remark']), "early" ) === false?trim(preg_replace("/\r|\n/", "", $row['remark'])):"";
			$result["early"] = '';//strpos( strtolower($row['remark']), "early" ) !== false?trim(preg_replace("/\r|\n/", "", $row['remark'])):"";
			$result["delayed"]='';
			$result["countryCode"] = $row['regionID']>0?qryToCommaSepString("SELECT country_code_3_chars FROM `tbl_country` where id=".$row['regionID']):'NA'; 
			

			
			$_1w = trim(strip_tags($row['1W']), $currencySymbolDefault);
			$_1m = trim(strip_tags($row['1M']), $currencySymbolDefault);
			$_3m = trim(strip_tags($row['3M']), $currencySymbolDefault);
			if($_1w!='' && $_1w!='NA' && $pageType=='post')
				$_1w = $isDoubleVal? number_format(str_replace(",","",$_1w)*$currencyConvertor, 1):number_format(str_replace(",","",$_1w)*$currencyConvertor);
			if($_1m!='' && $_1m!='NA' && $pageType=='post')
				$_1m = $isDoubleVal? number_format(str_replace(",","",$_1m)*$currencyConvertor, 1):number_format(str_replace(",","",$_1m)*$currencyConvertor);
			if($_3m!='' && $_3m!='NA' && $pageType=='post')
				$_3m = $isDoubleVal? number_format(str_replace(",","",$_3m)*$currencyConvertor, 1):number_format(str_replace(",","",$_3m)*$currencyConvertor);
			
			$result["1W"] = $pageType=='pre'?'hidden':(string)$_1w;
			$result["1M"] = $pageType=='pre'?'hidden':(string)$_1m;
			$result["3M"] = $pageType=='pre'?'hidden':(string)$_3m;
			if( isset($filter['deviceType']) && $filter['deviceType'] == 'ios'){
			//if( 0){
				$details = array(
					array("key" => 'Currency'	, "value"				=>			utf8_decode($row['currency'])),
					array("key" => 'Assessment'	, "value"	=>				isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment']),
					array("key" => 'Publication Day/Time'	, "value"	=>			utf8_decode($row['publication_day_time']))
				);				
			}
			else if( isset($filter['API_Key']) && $filter['API_Key'] == 'vByzPZgA5gdMP') {
				$details = array(
					'itemID'                => intval($row['id']),
					'Currency'				=>	utf8_decode($row['currency']),
					'Assessment'			=>	isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment'],
					'Publication Day/Time'	=>	utf8_decode($row['publication_day_time'])
					
				);		
			}
			else {
				$details = array(
					'Currency'				=>	utf8_decode($row['currency']),
					'Assessment'			=>	isset($row['assessmentText']) ? $row['assessmentText'] : $row['assessment'],
					'Publication Day/Time'	=>	utf8_decode($row['publication_day_time'])					
				);				
			}
			
			if($resourceType=='app'){
				$details = array_filter($details);
			}
			$result["details"] = $details;
			
			
			$result["parentID"]= $row['parentID'];
			$result["publicationDayTime"]= utf8_decode($row['publicationDayTime']);
	
				
			if($chkSource==true && $row['parentID']>0){
				//echo $row['parentID'].'--'.$row['id'].'<br>';
				if(!isset($mainEle[$row['parentID'].$f_cnf_fob]))
					$mainEle[$row['id'].$f_cnf_fob] = $result;				
				else
					$childEle[$row['parentID'].$f_cnf_fob][$row['id'].$f_cnf_fob] = $result;				
			}else{
				//$mainEle[] = $result;
				$mainEle[$row['id'].$f_cnf_fob] = $result;
				//$mainEle1[$row['id']] = $row['parentID'];
			} 
		
			if($pageType=='pre'){
				$content = 'hidden';
			}
		}
		
		if(isset($filter['debug']) && $filter['debug'] == 1) {
		echo "<pre>";
		print_r($mainEle);
		}
		
		$childArray = array_diff($parentEle1, array_keys($parentEle));	
		foreach($mainEle as $itemID=>$child):
			$childT = $child;
			foreach($childEle[$itemID] as $chilID=>$childArr){
				$child['viewMore'][$chilID]=$childArr;
				
				foreach($childEle[$chilID] as $subChilID=>$subChildArr){
					$child['viewMore'][$chilID]['viewMore'][$subChilID]=$subChildArr;
						
						foreach($childEle[$subChilID] as $subSubChilID=>$subSubChildArr){
							$child['viewMore'][$chilID]['viewMore'][$subChilID]['viewMore'][$subSubChilID]=$subSubChildArr;//4th levels
							$subChildArr['viewMore'][] = $subSubChildArr;
						}
					$childArr['viewMore'][] = $subChildArr;					
				}
				
				$childT['viewMore'][]=$childArr;
			}
			$prices[] = $child;
			$pricesT[] = $childT;
		endforeach;

        /*$finres = array();
        $finres["dataValue"] = $pricesT;
        $finres["cntValue"] = $rowsCnt;*/

        {
            return $pricesT;
        }

		//return $pricesT;
    }
    public static function getPriceSpreadRowsCnt($filter=array()){
		$startdate = $filter['fromdate'];
		$enddate = $filter['todate'];
		$rids = $filter['prices_assessments_to_show'];
		$whrCond = '';
		if( '' != $rids )
		    $whrCond = " and `spread_mst_id` in (" . $rids . ")  ";

        return qryToCommaSepString("
    			SELECT count(*) as cnt
    			FROM `tbl_spread_master` 
    			WHERE DATE(create_at) >= '$startdate'
    			and  DATE(create_at) <=  '$enddate'
    			$whrCond
    		");
		
	}

}

?>
