<?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);

class apiQuery{
	
	public static function getPackageDtlsOfMemid($memid){
		$a = file_get_contents("https://www.steelmint.com/mix_panel_function.php?id=$memid");
		
		return $a;
	}
	
	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://www.steelmint.com/steeladmin/wp_post_entry_in_sm_db.php?news_id=" . $postID . "&t=infographics");
		//include_once "/home/steelmin/public_html/inc/desconfig.php"; 
	}
	public static function actionsPostIntelPublish($postID){
        //include_once "/home/steelmin/public_html/inc/config1.php"; 
		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");
		//include_once "/home/steelmin/public_html/inc/desconfig.php"; 
	}	
	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://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);

		include_once "/home/steelmin/public_html/hf.php";
		updateJSONforAPPExplorePage();


/* 		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
		");
	
		
		//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";
	}

	public static function update_indexing_column($postID){
		$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
		";
		$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.

			$sql2="UPDATE tbl_news_post SET indexing='$sound' WHERE id=$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);			
		}
		
		$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"></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">';		
				$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   `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,
                            `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
							FROM `intel`  WHERE itemId>0 $no_ad  ";  
  		   
		   
		   
		   if(!isset($filters['post_id']) && !isset($filters['searchTerms']) )
			$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['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 .= ")";
			}else{
				$sql .= " AND (";
				$sql .= " continentID = " .  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'];
		}
		/* if(isset($filters['intelInsideInsight']) || $resourceType=='web') {
			$sql .= " AND `isAd` = 'n' ";
		} */
		$user = new User($memid, $appType);
		$isAccessible =  $user->isAccessible($resourceType, $section='Intel');
		if($isAccessible==-1 && !isset($filters['searchTerms'])){//post
		    if(!empty(Session::get('sectionFromDate'))){			
			    $sectionFromDate = Session::get('sectionFromDate');
		    	$sql .= " AND datePublished >= '$sectionFromDate'";			
		    }else{
				$sql .= " AND datePublished = '2001-01-01'";	
			}
		}
		
		//echo "at:" . $appType;
		
		$web_domain = $appType=='CM' ? "coalmint.com" : "steelmint.com";
			$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;
		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($limit != '')
			 $sql .= " LIMIT $offset,$limit";
			//echo "sql:" . $sql;
		
		if(isset($filters['debug']) && $filters['debug'] == 1) {
            echo "<br /><br /><pre>final sql:", $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"];
                $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);
				$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('</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";
				}*/
				
				$row["imageUrl"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", $row["imageUrl"]);
				$basename = basename($row["imageUrl"]);			
				$filename = dirname($row["imageUrl"]);				
				$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']
										);
				$result["Intels"][] = $row;
				/*if(
					(date("D") == "Mon" || date("D") == "Tue" || date("D") == "Wed") && 
					$cnt == 3 && 
					!isset($filters['dontShowAd']) &&
					!isset($filters["intelInsideInsight"])
				)*/
				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/Intel-Ad_7_4_2021.jpg";
                    $row["imageUrl"] = "https://www.steelmint.com/fileForMail/Intel-Ad_7_4_2021.jpg";
                    $row["ad_action"] = "open_url";
                    $row["type"] = "image";
                    $row["isAd"] = "y";
					$row["url_screen_name"]="https://youtu.be/_ykpTJTTyTI"; 
					$row["href"]="https://youtu.be/_ykpTJTTyTI"; 
					$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){
        //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";   
        $sql .= " order by postedDateTime desc";   
            switch($pageType){
               case 'post':
                        if(isset($filters["title"]) && $filters["title"] != null)
                                $sql .= " and f.`title` LIKE' %{$filters['title']}%";


                        if($limit)
                             $sql .= " limit {$offset},{$limit}";

               break;
               case 'pre':
                     $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 = '1' AND fp.post_id=".$rowk["itemID"]);$gallery = array();
				
				$views=0; $i = 0;
                while($row = mysql_fetch_array($secondary)){
                    if($row['type'] == "I" ){
                       $gallery[] = array(
											"ID"		=>	$row["id"],
											"mainImage"	=>	str_replace("https://www.steelmint.com","https://img.steelmint.com", $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","","http://img.youtube.com/vi/{$exp_v[1]}/hqdefault.jpg"),"videoUrl"=>$row["path"],"type"=>$row['type']); 
							if( $i == 0 ){
								$thumbImage = "http://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["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;
            }
			
         //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(''!=$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 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){
        //include_once "/home/steelmin/public_html/inc/config1.php";
		 $bookmark_array = explode(",",$bookmarks);
		 $is_bookmarked = $is_bookmark;
         $cond = '';
         if($event_id!=''){
             $cond = " WHERE sa.eventid={$event_id} and (sa.closed = 'Y' || sa.complementary = 'Y') ";
         }

         $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, 
                CASE 
                    when send_sms_to = 'R' then phoneno
                    else alternate_mob_no
                END as phoneno,
				c.country_code as 'flag',
				c.country, sa.`lastVisitiedOn`
            from tbl_members d
            left join final_status sa
            ON d.id=sa.registering_id
            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 $cond
            group by d.id
            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($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']),
							'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"
						);
					}
				  } 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'=>$row['job_title'],
						'company'=> htmlspecialchars_decode($row['company'], ENT_QUOTES),
						'email'=>strtolower($row['email']),
						'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"
					);
			}	
           
        }
		//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()){
        //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['memid'];
            $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 = "DESC";$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";
		}
		
         $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`,
       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 $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 registering_id = '{$registering_id}'";
        $event_sql = mysql_query($events_attended);
        while($row = mysql_fetch_array($event_sql,MYSQL_ASSOC)){
             $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"] = 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["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;

	}
	
	
	//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;
		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'
		$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' and resourceType='$resourceType'  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;
		}
		$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'  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)";
					$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);
				//if($memid==125073)print_r(session()->all());
				if($isAccessible==-1 && Session::get('userService') != 'Standard' && Session::get('userService') != 'Price Only' && Session::get('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('userType')!=1){
				//if(strpos(Session::get('sectionsIncludes'), "Insights") === false){
					$chkVisitHistoryCount = 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('userService') == 'Standard' || Session::get('userService') == 'Free Trial'){
					$chkVisitHistoryCount = 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('userService') == 'Price Only' ){
					$chkVisitHistoryCount = 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());
					}
				}
				
				$sql_qry = "UPDATE `tbl_news_post` SET `most_read` = (`most_read` + 1) WHERE `post_id` = " . (int)$filter['itemID'];

				mysql_query($sql_qry);
			}
			
			/*
			///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 = $filter['fromDate'];
			$sql .= " AND n.`post_date` >= '$dt'";
		}
		
		
		//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'){
    		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 .= " 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;
		else
			$limit = DEFAULT_NEWS_LIMIT;
		
		if(isset($filter['association_pmai']) && $filter['association_pmai'] == 'Y')
			$limit = 5;
		
		if(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>2nd sql:", $sql, "</pre>";
          print_r($filter);
        } 		
          // echo $sql; 
		$query = mysql_query($sql);
		$region='';$regionCnt = 0;
		$viewMore = array();
		while($row = mysql_fetch_assoc($query)){ 
			
			$result = array();
			//$result['itemId'] = strval($row['post_id']);
			$result['itemID'] = intval($row['post_id']);
			$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($pageType=='pre'){
				$content = 'hidden';
			}else{//if post
				$user = new User($memid, $appType);
				$isAccessible =  $user->isAccessible($resourceType, $section='Insights', $itemID='', $itemDate=$row['post_date']);
				
				if($isAccessible==-1){
					$pageType='post'; 
				}else{
					$pageType='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) && ($pageType=='pre' || Session::get('userService') == 'Standard' || Session::get('userService') == 'Price Only' || Session::get('userService') == 'Free Trial'))
			{
				if(empty(Session::get('userType'))){
					$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
					$pageType='post';
				}elseif(strpos(Session::get('sectionsIncludes'), "Insights") === false || Session::get('userService') == 'Standard' || Session::get('userService') == 'Price Only' || Session::get('userService') == 'Free Trial'){
				    $content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
					$pageType='post';
				}else{
					$content = 'hidden';
				}
			}elseif($pageType=='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')) ){
				$pageType='post';
				$content = removeMSWordattributes(html_entity_decode(stripslashes($row['post_content']), ENT_QUOTES));
			}
			if(isset($filter['is_blog']) && $filter['is_blog'] != '') {
				$pageType='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);				
			
			$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($resourceType == 'app') {
			    /*$content = preg_replace("/<span.*?>(.*)?<\/span>/i","$1", $content);*/
			    $content = preg_replace('/<span[^>]+\>/i', '', $content); 
				$content = str_replace("</span>","", $content);
			}    
			$result['description'] = $content;
			$result['f_tags'] = $row['f_tags'];	
			//$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['mainImageURL'] = str_replace("https://www.steelmint.com","https://img.steelmint.com", str_replace("http://", "https://", $row['image']));
			$basename = basename($result['mainImageURL']);			
			$filename = dirname($result['mainImageURL']);
			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;
				
			$result['thumbnailImageURL'] = $filename . "/tr:ar-2-1,w-200,c-at_max/" . $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['regionID'] = intval(end(explode(",",$row['regionIds'])));
			$result['regionID'] = intval($row['regionID']);
			$result['regionName'] = $row['regionName'];
			$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(), $pageType='post', $limit=5, $offset=0, $appType='SM'){
		//include_once "/home/steelmin/public_html/inc/config1.php";
		$result=array(); 
        $tenders = array();
		$currDate = date('Y-m-d H:i:s');
		///$cd = date('Y-m-d');
		$sql = "";				  
		$sql .= " WHERE n.`id` > 0 ";//and n.`post_id`<>107846
		//$sql .= " WHERE n.`id` > 0 and n.due_date <> '0000-00-00 00:00:00' and n.due_date > '$cd' ";//and n.`post_id`<>107846
		//RM_email
		
		if($source!='') {//source
			
			switch($source){				
				case 'listing':
				break;
				case 'mapView':
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'portfolio':
                    /* $common = new Common();
					$temp = $common->getUserPortfolioV2019($user_id, 'tenders', $appType);		
					 */
					 // and appType='".$appType."'
					$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;
					}
					/* if(empty($filter['commodityID']) && empty($filter['regionID'])){
						return new Response( json_decode(html_entity_decode(json_encode($result) ) ));
					} */
				   //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'home':
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'bookmarks':
				case 'bookmark':
                    /* $bookMarkedIds = qryToCommaSepString("select lead_id from tbl_bookmark as b where  user_id=$memid and section='tenders' and appType ='$appType' ");
					if($bookMarkedIds)
						$filter['itemID'] = explode(',', $bookMarkedIds);
					else
						$filter['itemID'] = 0; */
						
					$common = new Common();
					$bookMarkedIds = $common->getUserBookmarksV2019($resourceType, $memid, $section='tender', $status='', $event_id=0);
					//echo $bookMarkedIds;
					//$filter['itemID'] = explode(',', $bookMarkedIds);
					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[] = "REPLACE(UPPER(concat(title, sub_category_all, category_all, company_name, buy_sell,offer_type, c.country, state_name, region, description, remarks, floor_price, qty, grade)), ' ', '') LIKE '%" . mysql_real_escape_string($word) . "%'";
				//if( $memid == 116707 ){
					$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 . '[[:>:]]")   ';
				/* } else {
					$implode[] = " (title like '%$word%' OR sub_category_all  like '%$word%' OR  category_all like '%$word%'  OR  company_name like '%$word%'  OR  buy_sell like '%$word%'  OR offer_type like '%$word%'  OR  c.country like '%$word%'  OR  sc.state_name like '%$word%'  OR  region like '%$word%'  OR  description like '%$word%'  OR  remarks like '%$word%'  OR  floor_price like '%$word%'  OR  qty like '%$word%'  OR  grade like '%$word%'   OR  contact_person like '%$word%'   OR  email like '%$word%'    OR  mobile like '%$word%'   OR  product like '%$word%')   ";
				} */	
			}

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

			$sql .= ")";
		}   		
		
		//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{//
			
			//commodityID=> it can be any commodityID, subCommodityID or subsubCommodityID passed from API
			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 .= "((commodityID like '$commodityID' or commodityID like '$commodityID,%' or commodityID like '%,$commodityID')";
					$sql .= " OR ";
					$sql .= "(subCommodityId like '$commodityID' or subCommodityId like '$commodityID,%' or subCommodityId like '%,$commodityID'))";
				}
				$sql .= ")"; */
				
				/*$sqlTC = "select tender_id from tbl_tenders_commodity where tender_id>0"; 
				$sqlTC .= " AND ('";
					$sqlTC .= " `commodityID` IN ('";
					$sqlTC .= implode("', '", $filter['commodityID']);
					$sqlTC .= "') OR ";
					$sqlTC .= " `subCommodityID` IN ('";
					$sqlTC .= implode("', '", $filter['commodityID']);
					$sqlTC .= "')";
				$sqlTC .= "')";
				
				$tenderids = qryToCommaSepString($sqlTC);
				if($tenderids)
					$sql .= " AND n.`id` IN ($tenderids)";*/
					
				$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'])) {
				if($source == "mapView" || $source == "mapview"){
					$continents = implode("," , $filter['regionID']);
					$regions = qryToCommaSepString("select id from tbl_region_commodity_master where itemType = 'region' and (parentID in ($continents) OR id  in ($continents)) ");
				} else {
					$regions = implode(",", $filter['regionID']);
				}
				
				$sql .= " AND sc.`country_id` IN (" . $regions;
				$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 ";	
		}
		
		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)";	
			}
        }
		/* 
		$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['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($source=='mapview'){
			$sql .= " ORDER BY `country_name` DESC, n.`due_date` ASC";
		} */elseif($orderBY!=''){
			$sql .= " ORDER BY " . $orderBY;
		}else {
			//$sql .= " ORDER BY n.`due_date` ASC";
			$sql .= " ORDER BY 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;
		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
			  ";
         /* 
  (select group_concat(commodity_ID) from tbl_tenders_commodity where tender_id = n.id) as commodityID,
			  (select group_concat(sub_Commodity_ID) from tbl_tenders_commodity where tender_id = n.id) as subCommodityID, 		 
		  ttr.state_name,
			  ttr.country_name,
			  CASE
			  WHEN n.multi_loction = 1 THEN 'Multi Location'
			  WHEN ttr.country_name = 'INDIA' THEN concat(ttr.city_name,'/',ttr.state_name,'/',ttr.country_name)
			  ELSE concat(ttr.city_name, '/', ttr.country_name)
			  END as region,
			  
		 left join
			  tbl_tenders_region as ttr
			  on n.id = ttr.tender_id */
		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($filter), $sql, "</pre>";          
        }    
		
		$user = new User($memid, $appType);
		$isAccessible =  $user->isAccessible($resourceType, $section='Tenders');
		//print_r(Session::all());
		if(!empty(Session::get('sectionFromDate'))){
			$sectionFromDate = Session::get('sectionFromDate');
			$sectionTodate = Session::get('sectionTodate');			
		}
		//	echo $sql;
		//if($filter["update_count"] == 'Y'){
		if(isset($filter['tagID']) && strtolower($filter['tagID'])!='' ){
		    //echo $sql."\n\r";
		    $query = mysql_query($sql) or die(mysql_error().$sql);
		    //$tend_cnt = mysql_num_rows($query);
		    //echo "update tbl_tender_collection SET tenderCount='{$tend_cnt}' WHERE id ='{$filter['tagID']}'"."\n\r";
		    //mysql_query("update tbl_tender_collection SET tenderCount='{$tend_cnt}' WHERE id ='{$filter['tagID']}'");
		}
		$query = mysql_query($sql) or die(mysql_error().$sql);
		$region='';$regionCnt = 0;
		$viewMore = array();
		while($row = mysql_fetch_assoc($query)){ 			
			
			//if(!empty(Session::get('sectionFromDate')) && $pageType=='post'){
			if($isAccessible==-1 && $pageType=='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 = BASEURL. "api/public/assets/sm_default_medium.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'] = intval(end(explode(",",$row['commodityID'])));
			$result['subCommodityID'] = intval(end(explode(",",$row['subCommodityID'])));
			$result['regionID'] = intval(end(explode(",",$row['regionID']))); */
			/* $result['commodityID'] = intval(end(explode(",",$row['commodityID'])));
			$result['subCommodityID'] = intval(end(explode(",",$row['subCommodityID']))); */
			$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'] = $row['regionName'];
			
			$result['latitude'] = (double)$row['latitude'];
			$result['longitude'] = (double)$row['longitude'];
		//	$result['daysToGo'] = ($dateDiff>0) ? $dateDiff.' days to go':'';
			$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['openingDate'] = date('d M Y',strtotime($row['opening_date'])); 
			/* $result['dueDate'] = date('Y-m-d H:i:s',strtotime($row['dd']));
			$result['datePublished'] = date('Y-m-d H:i:s',strtotime($row['publish_date']));
			$result['openingDate'] = date('Y-m-d H:i:s',strtotime($row['opening_date'])); */
			
			//$row['state_name'] = ucwords(strtolower($row['state_name']));
           // $row['country_name'] = ucwords(strtolower($row['country_name']));
			
			//$result['location'] = $row['country_name'].', '.$row['state_name'];
			$result['location'] = ucwords(strtolower(str_replace('/', ', ',$row['region'])));
			
			$row['pdf_path'] = str_replace(' ', '%20',$row['pdf_path']);
            $result['document'] = $pageType=='pre'?'hidden':"https://www.steelmint.com/images/tenders/" . $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){
				//and appType='$appType'
				$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'] = $row['isAddedToPortfolio']!='' ? 'y':'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"		=>	""
								);
			
			
			//$re = explode(',',$row['region']);
			/* if($source=='mapview'){
				if(isset($filter['regionID'])){
					if(isset($mainEle[$row['state_name']])){
						$mainEle[$row['state_name']]['viewMore'][] = $result;
					}else{
						$mainEle[$row['state_name']] = $result; 
					}
				}else{
					if(isset($mainEle[$row['country_name']])){
						$mainEle[$row['country_name']]['viewMore'][] = $result;
					}else{
						$mainEle[$row['country_name']] = $result;
					}
				}
			}else{
				$mainEle[$tenderId] = $result;
			} */
			$tenders[]=$result;
		}
		
		
		/* foreach($mainEle as $ele):
			$tenders[]=$ele;
		endforeach; */
		
		if($type=='default'){
			//json file $tenders;
		}
		
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		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;
	}
	
	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","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"){		
			$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'
				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'
				$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);
		}
		} 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
			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
				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
				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
				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;
			
			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'];
		
		return qryToCommaSepString("
			SELECT count(*) as cnt
			FROM `$considerTableName` 
			WHERE `updated_on_date` >= '$startdate'
			and  `updated_on_date` <=  '$enddate'
			and `relation_id` in ($rids)
			and isAssessmentUpdated = 'Y'
		");
	}
	
	//DEFAULT_PRICES_LIMIT 
	public static function getPricesRows($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='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 .= "	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.`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";
		$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";
		}
		
		$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";

		$sql .= " WHERE m.`id` > 0 and n.`f_cnf_fob`<>'' and m.platform like '%$resourceType%'";
		
		/* 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 commodityID=408 then 1
							when commodityID=401 then 2
							when commodityID=410 then 3
							when commodityID=413 then 4
							when commodityID=403 then 5
							when commodityID=412 then 6
							else 99
						end, 
						case 
							when SubCommodityID=448 and zone = 'NORTH INDIA' then 1
							when SubCommodityID=448 and zone = 'EAST INDIA' then 2
							when SubCommodityID=448 and zone = 'CENTRAL INDIA' then 3
							when SubCommodityID=448 and zone = 'WEST INDIA' then 4
							when SubCommodityID=448 and zone = 'SOUTH INDIA' then 5
							else 99
						end"; */
		$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 = "";
		}
		
		if($source!='') {//source
			
			switch($source){				
				case 'indiaPrice':
				case 'indiaprice':
					$source= '';	
					$chkSource = false;
				break;
				case 'home':
				break;
				case 'bookmarks':
				case 'bookmark'://no bookmark for prices
                    //$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='prices' and appType ='$appType' ");
					if($bookMarkedIds)
						$filter['itemID'] = explode(',', $bookMarkedIds);
					else
						$filter['itemID'] = 0; */
					$chkSource = false;
				break;
				case 'portfolio':
                    $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 'recent':
				    //Recent / Latest - "Latest Insight" and "Recent Tenders" are same latest published ones to show
					//$portfolio['f'] = array(0);
				/*	$portfolio['cnf'] = array(195);
					//$portfolio['fob'] = array(0);
					$filter['itemID'] = $portfolio; 
					$source= '';
					$source= '';
					$chkSource = false; */
                    //$sql .= " AND DATE(n.`post_date`) > DATE_SUB(now(), INTERVAL 6 MONTH)";
				break;
				case 'alerts':
				case 'alert':
                   /*  $alertsIds = qryToCommaSepString("select item_id from tbl_alerts as b where  memid=$memid and section='price' ");//and appType ='$appType' 
					if($alertsIds)
						$filter['itemID'] = explode(',', $alertsIds);
					else
						$filter['itemID'] = 0; */
					///
					$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($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;
		}
		
		/*
		if(isset($filter['subType']) && !empty($filter['subType'])) {
			$key = $filter['subType']['key'];
			$value = $filter['subType']['value'];
			if( $key == 'Fines/Lumps' ){
				if( $value == 'Chhattisgarh' )
					$value = 'Chattisgarh';
				$cond = "  state = '$value' ";	
			} else if( $key == 'Pig Iron' ){
				$cond = "  f_grade = '$value' ";	
			} else if( $key == 'Sponge Iron' ){
				if( $value == 'PDRI' )
					$value = 'P-DRI';
				elseif( $value == 'CDRI' )
					$value = 'C-DRI';
				$cond = "  item = '$value' ";	
			}
			$subTypeIDs = qryToCommaSepString("select id from tbl_dom_master where $cond UNION select id from tbl_exim_master where $cond ");	
			$sql .= " AND m.`id` IN ($subTypeIDs) ";
		}*/
		
		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 updated_on_date >= '" . $filter['fromdate'] . "'";
			$sql .= " AND updated_on_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.`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 .= " )";	
					}
				}
			}
		}
		
		/* $web_domainweb_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['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']."'";
		}
		
		/* if(strtolower($source)=='mapview'){
			$sql .= " AND n.subCommodityID<>437 ";
		} */
        
		//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;
				
			} 

		
		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";
		}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";
		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 ";
		else
			$sql .= " AND n.showOnlyInSteelmint  = 1 AND n.continue_or_discontinue = 1";
		
		if(isset($filter['prices_assessments_to_show'])){
			$sql .= " AND n.isAssessmentUpdated = 'Y'";
		}
		/////price conversion
		/* $currencyINRTO = array(
			"INR"=>1,
			"USD"=>0.014,
			"YEN"=>1.51,
			"RUB"=>0.93,
			"RMB"=>0.1,
			"EUR"=>0.013,
			"EURO"=>0.013,
			"IDR"=>202.29,			
			"GBP"=>202.29,			
		);
		$currencyUSDTO = array(
			"INR"=>70,
			"USD"=>1,
			"YEN"=>106.75,
			"RUB"=>65.51,
			"RMB"=>7.04,					
			"EUR"=>1.09,
			"IDR"=>14281.8,				
			"EURO"=>1.09,		
			"GBP"=>1.09,		
		);
		 */
		$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'];
		}
		
		/* $symbolType = array(
            "INR"=>"20B9",
            "USD"=>"0024",
            "YEN"=>"00A5",
            "RUB"=>"20BD",
            "RMB"=>"00A5",
            "EUR"=>"20AC",
            "EURO"=>"20AC",
            "IDR"=>"0052,0070"        
            "GBP"=>"00A3"        
        ); */
		$currencyConvertor=1;
		
		if($source)
			$sql .= " and m.source like '%$source%'"; 
		//if($memid==56350)
		//	$sql .= " and m.id in(1047, 1037, 1036)"; 
		if(isset($filter['innerFilterCond']) && $filter['innerFilterCond'] != '')
			$chkSource=false;
	
		if($chkSource && $s_ids == '' && $source != 'keyindex_cm' && $source != 'keyindex' )
			$sql.=" and n.parentID=0";
		
		$flag = 0;	
		if(isset($filter['innerFilterCond']) && !in_array('tbl_dom_master', array_keys($filter['innerFilterCond'])) && $table=='tbl_exim_master'){
			$flag = 1;
		}
		
		/* if($memid==56350){
			echo '<pre>', print_r(array_keys($filter['innerFilterCond'])), '-',$flag, '-', '</pre>' ;
		} */
		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($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";
		}
		
		if(isset($filter['price_section_type']) )
			$limit = 8;
		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($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(strtolower($source)!='mapview'){//pagination concept not required for mapView
			$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
		} */
		
		/*if(isset($filter['fromdate']) && $filter['fromdate'] != '') {
			$sql = str_replace("tbl_price_static", "tbl_price_static_history", $sql);
		}*/
		
		if(isset($filter['considerTableName']) && $filter['considerTableName'] != '') {
			$sql = str_replace("tbl_price_static", $filter['considerTableName'], $sql);
		}
		
		if(isset($filter['debug']) && $filter['debug'] == 1) {
          echo "<pre>", $source, print_r($filter), $sql, "</pre>";
          ////die;
        }
		
             //echo "<pre>", $source, print_r($filter), $sql, "</pre>";
		$query = mysql_query($sql);
		if(isset($filter['debug']) && $filter['debug'] == 1) {
			echo "count: " . mysql_num_rows($query);
		}	
		$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("https://www.steelmint.com/nw/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)){ 
		
			$flag=$row['flag']!=''?strtolower($row['flag']):'noflag';			
			$sectionHeading='';
			$subSectionHeading='';
			if(strtolower($source)=='commodity' || strtolower($source)=='commoditywise' || (isset($filter['tabFilter']) || $filter['tabFilter']=='home')){
				/* $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);
			if(in_array($row['id'],$futureTblIds)){
				$datePublishedIN = 'CST';
			}else{
				$datePublishedIN = 'IST';
			}
			$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 = BASEURL."price/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"] = ($row['regionName']);
			$result["commodityID"] = intval($row['SubCommodityID']);
			$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["isAddedToPortfolio"] = $row['portfolio']!=0?'y':'n';
			$result["isSetAlert"] = $row['isSetAlert']!=''?'y':'n';
			$result["isBookmarked"] = "n";
			/* 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){
				$sqlTC = "select 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" => $currencySymbol,//"₹"
						  "name" => $_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';
			
			$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["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;
				if( $changeInPricePercentage >= 1 ){
					$changeInPricePercentage = round($changeInPricePercentage, 1);
				} else {
					$changeInPricePercentage = round($changeInPricePercentage, 1);
				}
				$_changeValue = round($_changeValue*$currencyConvertor,2);
			}else
				$changeInPricePercentage = '-';
			
			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 {
				$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']),
					'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["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($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 == 56350 ){
			if(isset($filter['mapp_css']) && $filter['mapp_css'] != ''){    
				
				$result["price"] = \ApiQuery::encodeVals($result["price"], $mapp);
				
				//$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($row['parentID']==0)
				$parentEle[$row['id']] = $row['parentID'];
			elseif(in_array($child['parentID'], array_keys($parentEle))===false)
				$parentEle1[$row['id']] = $row['parentID'];
			$mainEle[$row['id']] = $result; */
			
			if($pageType=='pre'){
				$content = 'hidden';
			}
			///$arrayCategories[$row['id']] = array("parentID" => $row['parentID'], "name" => $tradeType);
			////$prices[] = $result;
		}
		
		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;
		/* foreach($mainEle as $itemID=>$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=>$subChildArr)
							$child['viewMore'][$chilID]['viewMore'][$subChilID]['viewMore'][$subSubChilID]=$subChildArr;//4th levels
			}
			$prices[] = $child;
		endforeach; */
		
		
	/* 	
		foreach($mainEle as $itemID=>$child):
			if($child['parentID']==0){
				$prices[$itemID] = $child;
			}elseif(in_array($itemID, array_keys($childArray))!==false){
				$parentID = $childArray[$itemID];//
				$superParentID = $parentEle1[$parentID];//
				
				$prices[$superParentID]['l1'][$parentID]['l1'][$itemID] = $child;;
				
			}elseif(in_array($child['parentID'], array_keys($parentEle))!==false){
				//$prices[$child['parentID']]['l1'][$itemID] = $child;;
			}else{
				echo $superParent = $parentEle[$child['parentID']];
				///$prices[$child['parentID']]['l1'][] = $child;;
			}
			//$mainEle[$parentID]['viewMore']=$ele;
		endforeach; */
		//$currentParent=0; 		
		// \ApiQuery::createTreeView($mainEle, $currentParent, $currLevel = 0, $prevLevel = -1);

		
		/* foreach($childEle as $parentID=>$ele):
			$mainEle[$parentID]['viewMore']=$ele;
		endforeach; */
		
		/* foreach($mainEle as $iid=>$ele):
			foreach($childEle[$iid] as $parentID=>$childele):
				$ele['viewMore']=$childele;
			endforeach;
			
			$prices[]=$ele;
		endforeach; */
		
		if($type=='default'){
			//json file $news;
		}
		
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		return $pricesT;
    }

	function encodeVals($val, $arrEncodedNos){
	    $val = trim($val);
	    if( $val == "NA" || $val == "hidden" ||  $val == "")
	        return $val;
	    $val = strval($val);
	/*	$arrEncodedNos = array(
			"0"  => 'p202103311028431', 
			"1"  => 'p202103311028432', 
			"2"  => 'p202103311028433', 
			"3"  => 'p202103311028434', 
			"4"  => 'p202103311028435', 
			"5"  => 'p202103311028436', 
			"6"  => 'p202103311028437', 
			"7"  => 'p202103311028438', 
			"8"  => 'p202103311028439', 
			"9"  => 'p202103311028430',
			"."  => 'p2021033110284dot'				
		); */
		
		$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=''){
		//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' "; */
		
        $sqlTC = "select * from tbl_packages
                where  section = '$section'
                and platform = '$resourceType'
                $whrCond
                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)){
			
			$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']
			);
			$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;
		}
		/* 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']);
			$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 .= " ) ";
		}
		
		 $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;
	}
	
	//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';
		//include_once "/home/steelmin/public_html/inc/config1.php";
        $result=array(); 
        //$reports = array(); 
        //n.subCommodityID, n.`mapping`,
		$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 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();
		
		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='report' and appType ='$appType' ");
					 if($bookMarkedIds)
						$filter['itemID'] = explode(',', $bookMarkedIds);
					else
						$filter['itemID'] = 0; */
					$common = new Common();
					$bookMarkedIds = $common->getUserBookmarksV2019($resourceType, $memid, $section='report', $status='', $event_id=0);
					///print_r($bookMarkedIds);
					if(count($bookMarkedIds)>0)
						$filter['itemID'] = $bookMarkedIds;
					else
						$filter['itemID'] = array(0);
				break;
				
				case 'viewArchive':// by reportID
                    //$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)";
					
				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
			/*if(is_array($filter['itemID']))
				$sql .= " AND n.`id` IN (" . implode($filter['itemID']) .")";
			else
				$sql .= " AND n.`id` = " . (int)$filter['itemID'];*/
				
			$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(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 (";
				$sql .= " `commodityID` IN (";
				$sql .= implode(", ", $filter['commodityID']);
				$sql .= ")";
			$sql .= " OR ";	
				$sql .= " `subCommodityID` IN (";
				$sql .= implode(", ", $filter['commodityID']);
				$sql .= ")";
			$sql .= ")";*/
			/* $sql .= " AND `commodityID` IN (";
			$sql .= implode(", ", $filter['commodityID']);
			$sql .= ")"; */
			//$commodityID = implode(", ", $filter['commodityID']);
			//$sql .= " AND FIND_IN_SET({$commodityID},`commodityID`) > 0 ";
			$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 `regionID` IN (";
			$sql .= implode(", ", $filter['regionID']);
			$sql .= ")"; */	
			//$sql .= " AND FIND_IN_SET({$filter['regionID']},`regionID`) > 0 ";
			//$regionID = implode(", ", $filter['regionID']);
			///$sql .= " AND FIND_IN_SET({$regionID},`regionID`) > 0 ";
			/* steelreport - if we get region ID in teh filter then return all reports. we are not maintaining any region for steelreport table */
			/* $sql .= " AND (";
			foreach($filter['regionID'] as $k=>$regionID){
				if( $k> 0 )
					$sql .= " OR ";
				$sql .= " FIND_IN_SET({$regionID},`regionID`) > 0 ";
			}
			$sql .= " ) "; */
		}
		if($appType=='CM'){
			$web_domain = $appType=='CM' ? "coalmint.com" : "steelmint.com";
			/* $sql .= " AND MATCH(n.`website`) AGAINST ('";
			if(strpos($web_domain, "coalmint.com") !== false) {
				$sql .= "coalmint.com";
			} else {
				 $sql .= "steelmint.com";
			}
			$sql .= "' IN BOOLEAN MODE)"; */
		} 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";
		}
		
		//$sql .= " LIMIT " . (int)$offset . ", " . (int)$limit;
        //echo $sql;die;
        if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>main:", print_r($filter), $sql, "</pre>";
          
        } 
		$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' && !empty($bookMarkedIds)) 
				$_condition = " AND n.`id` IN (" . implode(',', $bookMarkedIds) .")";
			
			if($source=='viewArchive' || isset($filter['reportID']) || $source=='bookmarks' || $source=='bookmark') {
				$limitCond = " LIMIT " . (int)$offset . ", " . (int)$limit;
				$_innerPage = true;
			}else{
				$limitCond  = " LIMIT 0, 1" ;
				$_innerPage = false;
			}
			
			while($result = mysql_fetch_assoc($results)) {
				///$pageType='pre';
				/* if($pageType=='post')
					$maxCount_1 =  $user->getTakenServicesByUser($_rs_cat=$result['mapping'], $at_palce='reports',$GLOBALS['currDateTime']);
				if($maxCount_1==-1){
					$pageType='post';
				} */
								
				$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";
				/*CASE 
						WHEN '".$result['f_special_regular']."' = 's' THEN '" . $result['file'] . "' 
						ELSE (SELECT file FROM tbl_steelreport
						where steelreports_category_id = '".$result['category_id']."' 
						and FROM_UNIXTIME(date,'%Y-%m-%d') < date_sub(now(), interval 3 month) 
						order by date desc
						limit 0,1)
					END as sampleFileURL*/
				//and appType ='$appType'
				$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' and resourceType='$resourceType' 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 $sql;
		$query = mysql_query($sql) or die(mysql_error());
		$region='';$regionCnt = 0;
		//$viewMore = array();
		$result = array();
		
		while($row = mysql_fetch_assoc($query)){ 
						
			//if($pageType=='post'){
			if($pageType=='post'){
				//$maxCount_1 =  $user->getTakenServicesByUser($_rs_cat=$result['mapping'], $at_palce='reports',$GLOBALS['currDateTime']);
				/* if($memid>0 && $row['steelreports_category_id']==10){
					$isAccessible = -1;
				}else */if(in_array($memid, $GLOBALS['SPLRPT_MEMID_ALLOWED'])!==false && $row['steelreports_category_id']==5){
					$isAccessible = -1;
				}else{
					$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']);
				}
				if(isset($filter['debug']) && $filter['debug'] == 2) {
					echo '<br>'.$isAccessible.'---'.$row['steelreports_category_id'].'--'.date("Y-m-d", strtotime($row['fin_date'])).'--'.'Report_'.$row['db_value_f_special_regular'];
				} 
				//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);
			$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']),
                
                //"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'])),
                "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(strtolower($resourceType)=="app"){
			usort($result, array($result, "build_sorted"));
		} */
		
		//include_once "/home/steelmin/public_html/inc/desconfig.php";
		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'
						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 ('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;
		}
		
		if(isset($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'];
			
		$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>";
          
        }
        
		$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/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;
			/* $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'  ";
			
		}	
		
		$maxDateQuery = "SELECT MAX(sl.`excel_upoad_date_time`) FROM `tbl_logistic_data` sl WHERE sl.`id` > 0";
		$maxDateQuery .= " AND sl.`status` IN ('berth', 'anchorage', 'expected')";
	/*
	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";
		$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";

		$sql .= " FROM `tbl_logistic_data` l";
		//$sql .= " WHERE l.`id` > 0  $commCond ";
		$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['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 ('MET COKE', 'COKING COAL') ";
					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 .= "')";
				}
		   }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 .= "')";
				}
		   }			   
			
			/* 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'])) {
			$sql .= " AND l.`cargo` = '" . mysql_real_escape_string(trim($filter['cargo'])) . "'";
		}

		if($maxDateQuery) {
			$sql .= " AND DATE(l.`excel_upoad_date_time`) = 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 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){
				$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($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);
}
				
		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/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' )
			$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')  )";
		//	$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" : $week_prices[0]) : 0;
					$row['w-o-w'] = (isset($week_prices[0]) && isset($week_prices[1])) ? ($pageType=='pre' ? "hidden" :$week_prices[0] - $week_prices[1] ) : 0;
					$row['m-o-m'] = (isset($week_prices[0]) && isset($week_prices[4])) ? ($pageType=='pre' ? "hidden" : $week_prices[0] - $week_prices[4]) : 0;

					$row['assessment_title'] = isset($assessments[strtoupper($row['assessment'])]) ? $assessments[strtoupper($row['assessment'])] : '';
					
					$load_country = $row['load_country'];
					$commodity = $row['commodity'];
					unset($row['commodity']);
										
					$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/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($memid='',$commodityID=array(), $offset=0){
		//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;
		
		
		$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["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( $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;
    }
	
}

?>