<?php
namespace App\Http\Controllers\v2019;
use Illuminate\Http\Request;
use App\Http\Controllers\Auth\authentication;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
class IntelController extends Controller
{   
    public $appType = 'SM' ;
	public function __construct(Request $request) {
        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;			
        }
		$this->appType = 'SM';
		if($request->has('appType') && $request->input('appType') == true) {
            $this->appType = $request->input('appType');		
        } elseif($request->has('filters')){
			 $filter = $request->input('filters');
			 if(!empty($filter['app_type'])){
					$this->appType = 'CM';
			 }
		} elseif($request->has('app_type') && $request->input('app_type') == true) {
            $this->appType = $request->input('app_type');		
        }
		
	}
	
    public function getIntelByFilter(Request $request){
	   $sql = DB::table("intel")->where("1","=","1");
       if($request->input("filter")){
		   if($request->has("id") && $request->input("id") != null)
				$sql = $sql->where("id","=","1");
		   if($request->has("title") && $request->input("title") != null)
				$sql = $sql->where('title','LIKE',"%{$request->input("title")}%");		
	  }
	  return $sql;  
	}
    public function updateMostread(Request $request){
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			
			$post_id = 0;
			$count = 1;

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

			/* if($request->has('count') && (int)$request->input('count') > 0) {
				$count = $request->input('count');
			} */
			
			if($request->has('visitorID'))
		        $visitorID=$request->input('visitorID');	
		    else
		        $visitorID="";
		        
		    if($request->has('accessToken') && $request->input('accessToken')!=''){				
				$auth = new authentication();	
				$token = $request->input('accessToken');
				$user_id = $auth->authToken($token,$this->appType);
			}else{
			    $user_id = "";
			}
			
            //foreach($post_id as $p => $v ){
			for($i = 0; $i < count($post_id); $i++){
				$v = $post_id[$i];
				$sql = "UPDATE `intel` SET `most_read` = (`most_read` + 1) WHERE `itemId` = " . (int)$v;
				$sql_2 = "INSERT INTO `intel_stat_visit` SET `post_id`='". (int)$v."',`visitor_id`='".$visitorID."',`user_id`='".$user_id."',`f_time` = '".date("H:i:s")."',`f_date` = '".date("Y-m-d")."'";
				DB::statement($sql);
				DB::statement($sql_2);
				
				$update = "UPDATE tbl_intel_insight_hashmap AS to_update
							INNER JOIN intel AS update_from
							ON 	to_update.post_id = update_from.post_id 
							AND update_from.itemID = ".(int)$v ."
							SET to_update.most_read = update_from.most_read";
				DB::statement($update);
            }
			$code = 1001;
			$message = "Updated successfully";
		}else{
			$code = 1001;
			$message = "Limit of intel viewing exhausted for you!";
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	}
	public function getIntel(Request $request){
		$result = array();
		$resourceType = "APP";
		$limit = "Y";$total_count=0;$member=false;$visitor=false;
		$shareText = "Download SteelMint mobile application: https://www.steelmint.com/apps.php";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if($request->has('visitorID'))
		    $visitorID=$request->input('visitorID');	
		else
		    $visitorID="";
		$dumpForResponse = '';
		//if($request->has('itemIDs'))
			//$dumpForResponse .= "itemIds:" . $request->input('itemIDs');
			
		//$dumpForResponse .=  "visitorID:" . $visitorID; 	
		$totalAlreadyViewed = 0;
		$totalAllowedToView = 0;
		
		$totalAllowedToViewCnt = $this->appType=='CM'?2:5;
		
		$code = 1001;				
		$message = "Success";
		$offset=0;
		$user_id=0;
		//if($request->has('filter'))
		//	$type = $request->input('type');
		$filter = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filter = $request->input('filters');
			if( isset($filter['app_type']) && $filter['app_type'] == 'CM'){
				$shareText = "Download CoalMint mobile application: https://www.coalmint.com/apps.php";
				if(empty($filter['commodityID']))
					$filter['commodityID'] = array(401,407);//if coalmint then show only colamint related reports
			}
		}	
		if($request->has('pageValue')){
			$pageValue = $request->input('pageValue');					
		} else 
			$pageValue = 1;
		
		$offset = ($pageValue-1)* DEFAULT_LIMIT_INTEL;
		if (($request->has('accessToken') && $request->input('accessToken')!='') || ($request->has('memid') && $request->input('memid')!='')) {
			if($request->has('accessToken') && $request->input('accessToken')!=''){				
				$auth = new authentication();	
				$token = $request->input('accessToken');
				$user_id = $auth->authToken($token,$this->appType);
			}
			$dumpForResponse .=  "user_id:" . $user_id; 	

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

                if( !is_numeric($user_id) ){
                    return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
                }
				
				
			
			if ($user_id) {
				//DB::enableQueryLog(); 
				$selected_market='';
				if(isset($filter['selected_market'])){
                    $selected_market = $filter['selected_market'];
				}
				if(empty($selected_market) && $resourceType=='app'){
				    $comm=array();
                    $package = DB::table("tbl_updated_reg_logs_bm")
                    ->select('active_products','f_market')
                    ->where("memid","=",$user_id)
                    ->where("status","=","Active");           
                    if($this->appType=='CM'){
                        $package = $package->where("services","=","C");
                    }else{
                        if($resourceType == "web")
                        $package = $package->where("services","=","W");
                        if($resourceType == "app")
                        $package = $package->whereIn("services",["W", "MA", "MA_PO"]);
                    }
                    $package = $package->get();
                    $limit = "Y";
                    //print_r($package);
                    foreach($package as $k=> $v){                       
                        if(!empty($v["active_products"])){
                            $totalAllowedToViewCnt = $this->appType=='CM'?2:5;
                            $pkids = explode(",",$v["active_products"]);
                            $package_intel_accesible_count = DB::table("tbl_packages")->whereIn("id",$pkids)->where("is_intel_accessible","=","Y")->count();
                            if($package_intel_accesible_count > 0){ 
                                $mkt = explode(',',$v["f_market"]);                                
                                $mkt = array_map('trim', $mkt);
                                
                                $comm_qry =  DB::table("tbl_region_commodity_master")
                                        ->select(DB::raw('group_concat(ID) as commodityID'))
                                        ->where("itemType","=","commodity")
                                        ->where("parentID","<>",0)
                                        ->where(function($comm_qry) use ($mkt) {
                                            foreach ($mkt as $market) {
                                                $comm_qry->orWhereRaw("FIND_IN_SET(?, f_market)", [$market]);
                                            }
                                        })->first();
                                        //print_r($comm_qry);
                                        
                               if(!empty($comm_qry['commodityID']))
                                    $comm[] = $comm_qry['commodityID'];
                            }
                        }
                    }                    
                    if(!empty($comm)){
                         $all_comm = implode(",",$comm);
                         $filter['commodityID'] = array_unique(array_filter(explode(",",$all_comm)));   
                         $limit = "N";  
                    }
				}else{
				$package = DB::table("tbl_updated_reg_logs_bm")
				->select(DB::raw('group_concat(active_products) as prodIds'))
				->where("memid","=",$user_id)
				->where("status","=","Active");
				
				if($selected_market != '')
                        $package = $package->whereRaw("FIND_IN_SET('$selected_market', f_market)");
				
				if($this->appType=='CM'){
					$package = $package->where("services","=","C")->first();
				}else{
					if($resourceType == "web")
					   $package = $package->where("services","=","W")->first();

					if($resourceType == "app")
					   $package = $package->whereIn("services",["W", "MA", "MA_PO"])->first();
				}
				//dd(DB::getQueryLog());
				if(empty($package["prodIds"])){
					
					$limit = "Y";
				}

				if(!empty($package["prodIds"])){
                    $totalAllowedToViewCnt = $this->appType=='CM'?2:5;
					$pkids = explode(",",$package["prodIds"]);
					
					$package_intel_accesible_count = DB::table("tbl_packages")->whereIn("id",$pkids)->where("is_intel_accessible","=","Y")->count();
					
					if($package_intel_accesible_count == 0){
						$limit = "Y";
					} else {
						$limit = "N";
					}
				}
            }

			} else {

				$code = "2100" ;
				$message = "Access token is invalid or has expired";
				$result["Intels"] = array();

			}

		   $member =  true;
				
		} else {

		   $visitor = true;$limit = "Y";

		}
		$dumpForResponse .=  "limit:" . $limit; 
		//$filter['dump'] = $dumpForResponse;
		$itemID = $request->input('itemIDs');
		$items = explode(",",$itemID);
		//echo "<br />l:" . $limit;
		$testVar = '';
		if($limit == "Y"){
			 /////// limited ///////////////////////////////
			//////////////// insert viewed /////////////

			if(count($items) > 0){
				//echo "<pre>";
				//print_r($items);
				foreach($items as $k=>$v){
					if($v != ""){
						$count_already_viewed = 
						DB::table('tbl_intels_accessed_by_pre_login')
						->where("f_year","=",date('Y'))
						->where($member == true ?"memID":"visitorID","=",$member == true ?$user_id:$visitorID)
						->where("intelID","=",$v)
						->count();

						if($count_already_viewed > 0)
							continue;
				  
						DB::table("tbl_intels_accessed_by_pre_login")
						->insert(['f_date' => date("Y-m-d"), 
						'f_time' => date("H:i:s"),
						'f_year'=>date('Y'),$member == true ?"memID":"visitorID" => $member == true ?$user_id:$visitorID,
						'intelID'=>$v]
						);
					}
				}
			}

			$count_views_today = DB::table('tbl_intels_accessed_by_pre_login')
								->where("f_year","=",date('Y'))
								->where("f_date","=",date('Y-m-d'))
								->where($member == true ?"memID":"visitorID","=",$member == true ?$user_id:$visitorID)
								->select(DB::raw('distinct intelID'))
								->get();
			$count_views_today = count($count_views_today);
			
			if($count_views_today != $totalAllowedToViewCnt){
				if(isset($filter["post_id"]) && isset($filter["intelInsideInsight"]) && $filter["intelInsideInsight"] == 'Yes'){
					DB::table("tbl_intels_accessed_by_pre_login")
						->insert(['f_date' => date("Y-m-d"), 
						'f_time' => date("H:i:s"),
						'f_year'=>date('Y'),$member == true ?"memID":"visitorID" => $member == true ?$user_id:$visitorID,
						'intelID'=>$filter["post_id"]]
						);
				}			
			}
			$count_views_today = DB::table('tbl_intels_accessed_by_pre_login')
								->where("f_year","=",date('Y'))
								->where("f_date","=",date('Y-m-d'))
								->where($member == true ?"memID":"visitorID","=",$member == true ?$user_id:$visitorID)
								->select(DB::raw('distinct intelID'))
								->get();
			$count_views_today = count($count_views_today);
			
			$get_these_ids = DB::table("tbl_intels_accessed_by_pre_login")->select(DB::raw('group_concat(intelID) as Ids'))->where("f_year","=",date('Y'))->where("f_date","=",date('Y-m-d'))->where($member == true ?"memID":"visitorID","=",$member == true ?$user_id:$visitorID)->first();

			/////////////// process todays ///////////
				$exp_ids = array_values(array_filter(array_unique(explode(",",$get_these_ids['Ids']))));
				$filter["showIntel"] = "Y";	
				if(isset($filter["intelInsideInsight"]) && $filter["intelInsideInsight"] == 'Yes')
					$offsetForIntelInsideInsight = $offset;
				else 
					$offsetForIntelInsideInsight = 0;
				
				$totalAlreadyViewed = 0;
				$totalAllowedToView = 0;
				if($count_views_today == 0) {
					$testVar .= 's1';
					$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',5,$offsetForIntelInsideInsight,$this->appType);
/* 					if(isset($filter["post_id"]) && isset($filter["intelInsideInsight"]) && $filter["intelInsideInsight"] == 'Yes'){
						DB::table("tbl_intels_accessed_by_pre_login")
							->insert(['f_date' => date("Y-m-d"), 
							'f_time' => date("H:i:s"),
							'f_year'=>date('Y'),$member == true ?"memID":"visitorID" => $member == true ?$user_id:$visitorID,
							'intelID'=>$filter["post_id"]]
							);
					}		
 */					$totalAlreadyViewed = 0;
					$totalAllowedToView = $totalAllowedToViewCnt;
				} else if($count_views_today == $totalAllowedToViewCnt){
					if(isset($filter["post_id"]) && isset($filter["intelInsideInsight"]) && $filter["intelInsideInsight"] == 'Yes'){
						if (in_array($filter["post_id"], $exp_ids)){
							$filter["showIntel"] = "Y";	
						} else 
							$filter["showIntel"] = "N";	
					}
					$testVar .= 's2';
					$filter["itemID"] = $exp_ids;
					$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',5,$offsetForIntelInsideInsight,$this->appType);
					$totalAlreadyViewed = $totalAllowedToViewCnt;
					$totalAllowedToView = $totalAllowedToViewCnt;
				} else {
					if(isset($filter["intelInsideInsight"]) && $filter["intelInsideInsight"] == 'Yes'){
/* 						if( isset($filter["post_id"]) ){
							DB::table("tbl_intels_accessed_by_pre_login")
								->insert(['f_date' => date("Y-m-d"), 
								'f_time' => date("H:i:s"),
								'f_year'=>date('Y'),$member == true ?"memID":"visitorID" => $member == true ?$user_id:$visitorID,
								'intelID'=>$filter["post_id"]]
								);
						} */
						$testVar .= 's31';
						$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',$new_limit,$offsetForIntelInsideInsight,$this->appType);
					} else {
						$testVar .= 's3';
						$filter["itemID"] = $exp_ids;
						$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',5,$offsetForIntelInsideInsight,$this->appType);
						
						unset($filter['itemID']); 
						$filter["not_in"] = $exp_ids;
						$new_limit = $totalAllowedToViewCnt - count($exp_ids);
						$testVar .= 's4';
						$result_new = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',$new_limit,$offsetForIntelInsideInsight);
					}		
					$totalAlreadyViewed = $count_views_today;
					$totalAllowedToView = $totalAllowedToViewCnt;

					foreach($result_new['Intels'] as $k => $v){
						array_push($result['Intels'],$v);
					}
					//usort($result['Intels'], array($this, "build_sorted"));
				}
		} else {
			 ///////////// unlimited //////////////////////
			 $filter["showIntel"] = "Y";	
			if($pageValue>1){
				$testVar .= 's5';
				$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'post',DEFAULT_LIMIT_INTEL, $offset,$this->appType);	
			} else {
				$testVar .= 's6';
				$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'post',DEFAULT_LIMIT_INTEL,0,$this->appType);
			}
		}
		$total_count = DB::table('intel')
				->where("isAd","=","n")
				->where("datePublished","<=",date('Y-m-d 23:59:59'))
				->where("datePublished",">=",date('Y-m-d 00:00:00', strtotime('-7 days')));
				
		if( isset($filter['commodityID'])  ){
			$val = $filter['commodityID'];
			$total_count = $total_count -> where(function($query)  use ($val) {
							 $query -> whereIn("commodityID",$val)
								-> orWhereIn ("subCommodityID",$val)
								-> orWhereIn ("subSubCommodityID",$val);
							});							
		}
		
		if( isset($filter['regionID'])  ){
			$val = $filter['regionID'];
			$total_count = $total_count -> WhereIn ("regionID",$val);							
		} 	
		
		if( isset($filter['searchTerms'])  )
			$total_count = $result["intelCount"];
		else
			$total_count = $total_count -> count();
		
		if( isset($filter['debug']) && $filter['debug'] == 1){
			echo "<pre>" . $total_count;
			echo "<br />" . $testVar;
		}
		/* echo "<pre>" . $total_count;
			print_r($result["Intels"]);	 */
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result["Intels"],"dump"=>$dumpForResponse,"count"=>$total_count,"limit"=>$limit,"totalAlreadyViewed"=>$totalAlreadyViewed,"totalAllowedToView"=>$totalAllowedToView,"shareText" => $shareText));
	}
	
	private function build_sorted ($a, $b){
        if ($a["itemID"] == $b["itemID"]) {
            return 0;
        }
        return ($a["itemID"] > $b["itemID"]) ? -1 : 1;
    }
	public function getIntel_2_per_weeks_concept(Request $request)
    {      
		$result = array();
		$resourceType = "APP";
		$limit = "Y";$total_count=0;
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$code = 1001;				
		$message = "Success";
		$offset=0;
		$user_id=0;
		if($request->has('filter'))
		    $type = $request->input('type'); 
     
			if($resourceType=='web'){

					$pageValue = $request->input('pageValue');					
					$offset = ($pageValue-1)* DEFAULT_LIMIT;
					
						if($pageValue>1){//run query here
	                        $result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'post',DEFAULT_LIMIT, $offset,$this->appType);
						}else {/// data from json array file 
							$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'post',DEFAULT_LIMIT,0,$this->appType);
						}


/*	//following code commented by tarun on 14-03-2020 as website was not sending memid. so, for time being bypassing teh need of  memid from website side			
                if ($request->has('memid') && $request->input('memid')!=''){
					$pageValue = $request->input('pageValue');					
					$offset = ($pageValue-1)* DEFAULT_LIMIT;
					
					$memid = $request->input('memid');
					$auth = new authentication();
					$user_id = $auth->authUserId($memid);//for web user
					if ($user_id) {
						if($pageValue>1){//run query here
	                        $result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'post',DEFAULT_LIMIT, $offset);
						}else {/// data from json array file 
							$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'post',DEFAULT_LIMIT,0);
						}
					}else{
						$code = 2013;
						$message = "Unauthorized action.";
					}
					
				}else{
					//$result = \apiQuery::getIntelRowSet($resourceType, $type='', $filter=array(),'pre',DEFAULT_LIMIT, 0);
					$result = array("NO - List to be shown.");
				}								
*/				
		    }else {
				    
				if ($request->has('accessToken') && $request->input('accessToken')!='') {				
					$auth = new authentication();	
					$token = $request->input('accessToken');
					$user_id = $auth->authToken($token,$this->appType);	
					
					$pageValue = $request->input('pageValue');					
					$offset = ($pageValue-1)* DEFAULT_LIMIT;
					
					if ($user_id) {
					
                        //DB::enableQueryLog(); 
						$package = DB::table("tbl_reg_logs")->select(DB::raw('group_concat(selected_products) as prodIds'))->where("memid","=",$user_id)->where("status","=","Active")->first();
						//dd(DB::getQueryLog());
						
						if(empty($package["prodIds"])){
							
							$limit = "Y";
							////////////////// repeat /////////////////// 
							$itemID = $request->input('itemIDs');
					
							$week = DB::table("tbl_year_week")->select("year","week")->where("monday","<=",date('Y-m-d'))->where("sunday",">=",date('Y-m-d'))->first();
							//DB::enableQueryLog(); 
		
							///////insert viewed by app////////////////////////////
							$items = explode(",",$itemID);
							//print_r($items);
							if(count($items) > 0){
							foreach($items as $k=>$v){
								if($v != ""){
								$count_already_viewed = DB::table('tbl_intels_accessed_by_pre_login')->where("f_year","=",$week["year"])->where("memID","=",$user_id)->where("intelID","=",$v)->count();
		
								if($count_already_viewed > 0)
								continue;
		
								DB::table("tbl_intels_accessed_by_pre_login")->insert(['f_date' => date("Y-m-d"), 'f_time' => date("H:i:s"),'weekNo'=> $week["week"], 'f_year'=>$week["year"],'memID'=> $user_id,'intelID'=>$v]);
								}
							}
						}
		
							$count_views_by_visitor = DB::table('tbl_intels_accessed_by_pre_login')->where("f_year","=",$week["year"])->where("weekNo","=",$week["week"])->where("memID","=",$user_id)->count();
							
							// dd(DB::getQueryLog()); 
							$swap = array();
							if($count_views_by_visitor == 0){
						    	$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'pre',DEFAULT_LIMIT, 0, $this->appType);
								///apend/////////older///////////
								$ids = array();
								$all_past_viewed = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("memID","=",$user_id)->where("f_year","=",$week["year"])->where("weekNo","<",$week["week"])->get();
								foreach($all_past_viewed as $k=> $v){
								$ids[] = $v["intelID"];
								}
								$results = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("itemID"=>$ids,"orderBy"=>"created_at"),'post',DEFAULT_LIMIT, 0, $this->appType);
								/*foreach($results["Intels"] as $k=> $v){
									array_push($result["Intels"],$v);
								}*/
								foreach($results["Intels"] as $k=> $v){
									$v["is_new"] = "N";
									foreach($result["Intels"] as $m => $y){
										if($v["itemID"] == $y["itemID"]){
											$result["Intels"][$m] = "";
										}
									}
									 array_push($result["Intels"],$v);
								 }
		
								 foreach($result["Intels"] as $r => $s){
									   if(is_array($s)){
										 array_push($swap,$s);
									   }
								}
								$result["Intels"] = $swap;
							} else if($count_views_by_visitor == 1){
		
								$get_next_id = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("f_year","=",$week["year"])->where("weekNo","=",$week["week"])->where("memID","=",$user_id)->first();
							
							
								$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("not_in"=>$get_next_id["intelID"]),'pre_1',DEFAULT_LIMIT, 0, $this->appType);
								///apend/////////older///////////
								$ids = array();
								$all_past_viewed = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("memID","=",$user_id)->where("f_year","=",$week["year"])->where("weekNo","<=",$week["week"])->get();
								foreach($all_past_viewed as $k=> $v){
								$ids[] = $v["intelID"];
								}
								$results = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("itemID"=>$ids,"orderBy"=>"created_at"),'post',DEFAULT_LIMIT, 0, $this->appType);
								/*foreach($results["Intels"] as $k=> $v){
									array_push($result["Intels"],$v);
								}*/

								foreach($results["Intels"] as $k=> $v){
									$v["is_new"] = "N";
									foreach($result["Intels"] as $m => $y){
										if($v["itemID"] == $y["itemID"]){
											$result["Intels"][$m] = "";
										}
									}
									 array_push($result["Intels"],$v);
								 }
		
								 foreach($result["Intels"] as $r => $s){
									   if(is_array($s)){
										 array_push($swap,$s);
									   }
								}
								$result["Intels"] = $swap;
							} else {
								$ids = array();
								$all_past_viewed = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("memID","=",$user_id)->get();
								foreach($all_past_viewed as $k=> $v){
								$ids[] = $v["intelID"];
								}
								$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("itemID"=>$ids,"orderBy"=>"created_at"),'post',DEFAULT_LIMIT, 0, $this->appType);
							}
						} 

						if(!empty($package["prodIds"])){
							$pkids = explode(",",$package["prodIds"]);
							
							$package_intel_accesible_count = DB::table("tbl_packages")->whereIn("id",$pkids)->where("is_intel_accessible","=","Y")->count();//dd(DB::getQueryLog());
							if($package_intel_accesible_count == 0){
								$limit = "0";
								
							} else {
								$limit = "N";
								if($pageValue>1){
									$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'post',DEFAULT_LIMIT, $offset, $this->appType);	
									$total_count = DB::table('intel')->where("isAd","=","n")->count();   
								}else {
									$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'post',DEFAULT_LIMIT,0, $this->appType);
									$total_count = DB::table('intel')->where("isAd","=","n")->count();
								}
							}
						}
						
						
						
					} else {
						
						$code = "2100" ;
						$message = "Access token is invalid or has expired";
						$result["Intels"] = array();
					}

				}else{
					
					$itemID = $request->input('itemIDs');
					
					$week = DB::table("tbl_year_week")->select("year","week")->where("monday","<=",date('Y-m-d'))->where("sunday",">=",date('Y-m-d'))->first();
					//DB::enableQueryLog(); 

					///////insert viewed by app////////////////////////////
					$items = explode(",",$itemID);
					//print_r($items);
					if(count($items) > 0){
					foreach($items as $k=>$v){
						if($v != ""){
						$count_already_viewed = DB::table('tbl_intels_accessed_by_pre_login')->where("f_year","=",$week["year"])->where("visitorID","=",$request->input('visitorID'))->where("intelID","=",$v)->count();

						if($count_already_viewed > 0)
						continue;

						DB::table("tbl_intels_accessed_by_pre_login")->insert(['f_date' => date("Y-m-d"), 'f_time' => date("H:i:s"),'weekNo'=> $week["week"], 'f_year'=>$week["year"],'visitorID'=> $request->input('visitorID'),'intelID'=>$v]);
						}
					}
				}

					$count_views_by_visitor = DB::table('tbl_intels_accessed_by_pre_login')->where("f_year","=",$week["year"])->where("weekNo","=",$week["week"])->where("visitorID","=",$request->input('visitorID'))->count();
					
					// dd(DB::getQueryLog()); 
					$swap = array();
					if($count_views_by_visitor == 0){
					   $result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array(),'pre',DEFAULT_LIMIT, 0, $this->appType);
					   //print_r($result["Intels"]);

					    ///apend/////////older///////////
					    $ids = array();
						$all_past_viewed = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("visitorID","=",$request->input('visitorID'))->where("f_year","=",$week["year"])->where("weekNo","<",$week["week"])->get();
						foreach($all_past_viewed as $k=> $v){
                        $ids[] = $v["intelID"];
						}
						$results = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("itemID"=>$ids,"orderBy"=>"created_at"),'post',DEFAULT_LIMIT, 0, $this->appType);
						//print_r($results["Intels"]);
						foreach($results["Intels"] as $k=> $v){
							$v["is_new"] = "N";
							foreach($result["Intels"] as $m => $y){
								if($v["itemID"] == $y["itemID"]){
									$result["Intels"][$m] = "";
								}
							}
							
							array_push($result["Intels"],$v);
						}

						foreach($result["Intels"] as $r => $s){
                               if(is_array($s)){
								 array_push($swap,$s);
							   }
						}
						$result["Intels"] = $swap;
						///print_r($result["Intels"]);
					} else if($count_views_by_visitor == 1){

						$get_next_id = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("f_year","=",$week["year"])->where("weekNo","=",$week["week"])->where("visitorID","=",$request->input('visitorID'))->first();
						
						
					     $result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("not_in"=>$get_next_id["intelID"]),'pre_1',DEFAULT_LIMIT, 0, $this->appType);
					     ///apend/////////older///////////
						 $ids = array();
						 $all_past_viewed = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("visitorID","=",$request->input('visitorID'))->where("f_year","=",$week["year"])->where("weekNo","<=",$week["week"])->get();
						 foreach($all_past_viewed as $k=> $v){
						 $ids[] = $v["intelID"];
						 }
						 $results = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("itemID"=>$ids,"orderBy"=>"created_at"),'post',DEFAULT_LIMIT, 0, $this->appType);
						 foreach($results["Intels"] as $k=> $v){
							$v["is_new"] = "N";
							foreach($result["Intels"] as $m => $y){
								if($v["itemID"] == $y["itemID"]){
									$result["Intels"][$m] = "";
								}
							}
							 array_push($result["Intels"],$v);
						 }

						 foreach($result["Intels"] as $r => $s){
                               if(is_array($s)){
								 array_push($swap,$s);
							   }
						}
						$result["Intels"] = $swap;

					} else {
						$ids = array();
						$all_past_viewed = DB::table('tbl_intels_accessed_by_pre_login')->select("intelID")->where("visitorID","=",$request->input('visitorID'))->get();
						foreach($all_past_viewed as $k=> $v){
                        $ids[] = $v["intelID"];
						}
					    $result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter=array("itemID"=>$ids,"orderBy"=>"created_at"),'post',DEFAULT_LIMIT, 0, $this->appType);
					}

                    

					$code = 1001;
					$message = "Success";
				}
			}	
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result["Intels"],"count"=>$total_count,"limit"=>$limit));
    }  
	
	public function getIntelTrending(Request $request)
    {      
		$result = array();
		include_once "/home/steelmin/public_html/api/storage/v2019/intel_trending_post.php";
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
           // $auth = new authentication();
           $token = $request->input('accessToken');
           if(empty($token)){
			   $code = 2013;
				$message = "User not found.";
			}else{
				$code = 1001;
				$message = "Success";
			}
        }else{
			
			$code = 1001;
			$message = "Success";
		}
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }
	
	public function getIntelDetails(Request $request){
		$resourceType = "app";
		$source = "listing";
		$result = array();	
		$shareText = "Download SteelMint mobile application: https://www.steelmint.com/apps.php";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$filter = array();
		if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters');
		if( isset($filters['app_type']) && $filters['app_type'] == 'CM')
			$shareText = "Download CoalMint mobile application: https://www.coalmint.com/apps.php";
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			$filters['post_id'] = $itemID;
		}else{
			$code = 2013;
			$message = "Invalid! itemID missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		$memid=0;
		if($resourceType=='app' && $request->has('accessToken') && !empty($request->input('accessToken'))){
		    $auth = new authentication();	
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token,$this->appType);	
		}elseif($resourceType=='web' && $request->has('memid') && !empty($request->input('memid'))){
			//$memid = $request->input('memid');
			    $memid = htmlentities($request->input('memid'), ENT_QUOTES);

                if( !is_numeric($memid) ){
                    return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
                }
			
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
			
			
			if(empty($filters['selected_market']) && $resourceType=='app' && !empty($memid)){
                $user = new User($memid, $this->appType);
                $filters['selected_market'] =  $user->getMarketForAPPByItemID($resourceType,$itemID,'intel');                
			}
			
		}	
		////$filters['debug'] = 1;
		
		$resultDetails = \apiQuery::getIntelRowSet($user_id=$memid, $resourceType, $type='', $filters,'post',1,0,$this->appType);
		///print_R($resultDetails);
		if(count($resultDetails)>0  && $resourceType!='app'){
			$result = $resultDetails['Intels'][0];
		}else{
			$result = $resultDetails['Intels'];
		}
		$code = 1001;
		$message = "Success";
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result,"shareText" => $shareText));
	}
	
	public function insertIntelVisitor(Request $request){

		$week = DB::table("tbl_year_week")->select("year","week")->where("monday","<=",date('Y-m-d'))->where("sunday",">=",date('Y-m-d'))->first();
        DB::table("tbl_intels_accessed_by_pre_login")->insert(['f_date' => date("Y-m-d"), 'f_time' => date("H:i:s"),'weekNo'=> $week["week"], 'f_year'=>$week["year"],'visitorID'=> $request->input('visitorID'),'intelID'=>$request->input('intelID')]);
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	}
	
	//added for listing intel in app - when selected_market key is blank
	public function getIntellist(Request $request){
        $result = array();
		$resourceType = "APP";
		$limit = "Y";$total_count=0;$member=false;$visitor=false;
		$shareText = "Download SteelMint mobile application: https://www.steelmint.com/apps.php";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		if($request->has('visitorID'))
		    $visitorID=$request->input('visitorID');	
		else
		    $visitorID="";
		$dumpForResponse = '';		
		$totalAlreadyViewed = 0;
		$totalAllowedToView = 0;
		
		$totalAllowedToViewCnt = $this->appType=='CM'?2:5;
		$code = 1001;				
		$message = "Success";
		$offset=0;
		$user_id=0;
		
		$filter = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filter = $request->input('filters');
		}	
		if($request->has('pageValue')){
			$pageValue = $request->input('pageValue');					
		} else 
			$pageValue = 1;
		$offset = ($pageValue-1)* DEFAULT_LIMIT_INTEL;
		if (($request->has('accessToken') && $request->input('accessToken')!='') || ($request->has('memid') && $request->input('memid')!='')) {
			if($request->has('accessToken') && $request->input('accessToken')!=''){				
				$auth = new authentication();	
				$token = $request->input('accessToken');
				$user_id = $auth->authToken($token,$this->appType);
			}
			$dumpForResponse .=  "user_id:" . $user_id; 	
			if($request->has('memid') && $request->input('memid')!='')
				//$user_id = $request->input('memid');
			    $user_id = htmlentities($request->input('memid'), ENT_QUOTES);
                if( !is_numeric($user_id) ){
                    return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
                }
			if ($user_id) {				
				$selected_market='';
				if(isset($filter['selected_market'])){
                    $selected_market = $filter['selected_market'];
				}
				
				if(empty($selected_market) && $resourceType=='app'){
				    $comm=array();
                    $package = DB::table("tbl_updated_reg_logs_bm")
                    ->select('active_products','f_market')
                    ->where("memid","=",$user_id)
                    ->where("status","=","Active");           
                    if($this->appType=='CM'){
                        $package = $package->where("services","=","C");
                    }else{
                        if($resourceType == "web")
                        $package = $package->where("services","=","W");
                        if($resourceType == "app")
                        $package = $package->whereIn("services",["W", "MA", "MA_PO"]);
                    }
                    $package = $package->get();
                    $limit = "Y";
                    //print_r($package);
                    foreach($package as $k=> $v){                       
                        if(!empty($v["active_products"])){
                            $totalAllowedToViewCnt = $this->appType=='CM'?2:5;
                            $pkids = explode(",",$v["active_products"]);
                            $package_intel_accesible_count = DB::table("tbl_packages")->whereIn("id",$pkids)->where("is_intel_accessible","=","Y")->count();
                            if($package_intel_accesible_count > 0){ 
                                $mkt = explode(',',$v["f_market"]);                                
                                $mkt = array_map('trim', $mkt);
                                
                                $comm_qry =  DB::table("tbl_region_commodity_master")
                                        ->select(DB::raw('group_concat(ID) as commodityID'))
                                        ->where("itemType","=","commodity")
                                        ->where("parentID","<>",0)
                                        ->where(function($comm_qry) use ($mkt) {
                                            foreach ($mkt as $market) {
                                                $comm_qry->orWhereRaw("FIND_IN_SET(?, f_market)", [$market]);
                                            }
                                        })->first();
                                        //print_r($comm_qry);
                                        
                               if(!empty($comm_qry['commodityID']))
                                    $comm[] = $comm_qry['commodityID'];
                            }
                        }
                    }                    
                    if(!empty($comm)){
                         $all_comm = implode(",",$comm);
                         $filter['commodityID'] = array_unique(array_filter(explode(",",$all_comm)));   
                         $limit = "N";  
                    }
				}
				else{
                    $package = DB::table("tbl_updated_reg_logs_bm")
                    ->select(DB::raw('group_concat(active_products) as prodIds'))
                    ->where("memid","=",$user_id)
                    ->where("status","=","Active");
                    if($selected_market != '')
                            $package = $package->whereRaw("FIND_IN_SET('$selected_market', f_market)");
                    if($this->appType=='CM'){
                        $package = $package->where("services","=","C")->first();
                    }else{
                        if($resourceType == "web")
                        $package = $package->where("services","=","W")->first();
                        if($resourceType == "app")
                        $package = $package->whereIn("services",["W", "MA", "MA_PO"])->first();
                    }
                    //dd(DB::getQueryLog());
                    if(empty($package["prodIds"])){
                        $limit = "Y";
                    }
                    if(!empty($package["prodIds"])){
                        $totalAllowedToViewCnt = $this->appType=='CM'?2:5;
                        $pkids = explode(",",$package["prodIds"]);
                        $package_intel_accesible_count = DB::table("tbl_packages")->whereIn("id",$pkids)->where("is_intel_accessible","=","Y")->count();
                        if($package_intel_accesible_count == 0){
                            $limit = "Y";
                        } else {
                            $limit = "N";
                        }
                    }
				}
			} else {
				$code = "2100" ;
				$message = "Access token is invalid or has expired";
				$result["Intels"] = array();
			}
		   $member =  true;
		} else {
		   $visitor = true;$limit = "Y";
		}
		$dumpForResponse .=  "limit:" . $limit; 
		//$filter['dump'] = $dumpForResponse;
		$itemID = $request->input('itemIDs');
		$items = explode(",",$itemID);
		//echo "<br />l:" . $limit;
		$testVar = '';
		if($limit == "Y"){
			$count_views_today = DB::table('tbl_intels_accessed_by_pre_login')
								->where("f_year","=",date('Y'))
								->where("f_date","=",date('Y-m-d'))
								->where($member == true ?"memID":"visitorID","=",$member == true ?$user_id:$visitorID)
								->select(DB::raw('distinct intelID'))
								->get();
			$count_views_today = count($count_views_today);
			$get_these_ids = DB::table("tbl_intels_accessed_by_pre_login")
                            ->select(DB::raw('group_concat(intelID) as Ids'))
                            ->where("f_year","=",date('Y'))
                            ->where("f_date","=",date('Y-m-d'))
                            ->where($member == true ?"memID":"visitorID","=",$member == true ?$user_id:$visitorID)
                            ->first();
			/////////////// process todays ///////////
				$exp_ids = array_values(array_filter(array_unique(explode(",",$get_these_ids['Ids']))));
				$filter["showIntel"] = "Y";	
				$offsetForIntelInsideInsight = 0;
				$totalAlreadyViewed = 0;
				$totalAllowedToView = 0;
				if($count_views_today == 0) {
					$testVar .= 's1';
					$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',5,$offsetForIntelInsideInsight,$this->appType);	
 					$totalAlreadyViewed = 0;
					$totalAllowedToView = $totalAllowedToViewCnt;
				} else if($count_views_today == $totalAllowedToViewCnt){				
					$testVar .= 's2';
					$filter["itemID"] = $exp_ids;
					$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',5,$offsetForIntelInsideInsight,$this->appType);
					$totalAlreadyViewed = $totalAllowedToViewCnt;
					$totalAllowedToView = $totalAllowedToViewCnt;
				} else {                    
                    $testVar .= 's3';
                    $filter["itemID"] = $exp_ids;
                    $result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',5,$offsetForIntelInsideInsight,$this->appType);
                    unset($filter['itemID']); 
                    $filter["not_in"] = $exp_ids;
                    $new_limit = $totalAllowedToViewCnt - count($exp_ids);
                    $result_new = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'pre',$new_limit,$offsetForIntelInsideInsight);							
					$totalAlreadyViewed = $count_views_today;
					$totalAllowedToView = $totalAllowedToViewCnt;
					foreach($result_new['Intels'] as $k => $v){
						array_push($result['Intels'],$v);
					}
				}
		} else {
			 ///////////// unlimited //////////////////////
			 $filter["showIntel"] = "Y";	
			if($pageValue>1){
				$testVar .= 's5';
				$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'post',DEFAULT_LIMIT_INTEL, $offset,$this->appType);	
			} else {
				$testVar .= 's6';
				$result = \apiQuery::getIntelRowSet($user_id, $resourceType, $type='', $filter,'post',DEFAULT_LIMIT_INTEL,0,$this->appType);
			}
		}
		$total_count = DB::table('intel')
				->where("isAd","=","n")
				->where("datePublished","<=",date('Y-m-d 23:59:59'))
				->where("datePublished",">=",date('Y-m-d 00:00:00', strtotime('-7 days')));
		if( isset($filter['commodityID'])  ){
			$val = $filter['commodityID'];
			$total_count = $total_count -> where(function($query)  use ($val) {
							 $query -> whereIn("commodityID",$val)
								-> orWhereIn ("subCommodityID",$val)
								-> orWhereIn ("subSubCommodityID",$val);
							});							
		}
		if( isset($filter['regionID'])  ){
			$val = $filter['regionID'];
			$total_count = $total_count -> WhereIn ("regionID",$val);							
		} 	
		if( isset($filter['searchTerms'])  )
			$total_count = $result["intelCount"];
		else
			$total_count = $total_count -> count();
		if( isset($filter['debug']) && $filter['debug'] == '1'){
			echo "<pre>total count" . $total_count."===== visitor".$visitorID;
			echo "<br />test - " . $testVar;
			print_r($filter);
			echo "<//pre>";
		}
		/*  . $total_count;
			print_r($result["Intels"]);	 */
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result["Intels"],"dump"=>$dumpForResponse,"count"=>$total_count,"limit"=>$limit,"totalAlreadyViewed"=>$totalAlreadyViewed,"totalAllowedToView"=>$totalAllowedToView,"shareText" => $shareText));
	}
}
