<?php
namespace App\Http\Controllers\v2019;
include_once "/home/steelmin/public_html/inc/config1.php";
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Auth\User;
use App\Http\Controllers\Auth\authentication;
use Session;

class InfographController extends Controller{

  public function getInfograph(Request $request){
    $result = array(); 
    $v = app('App\Http\Controllers\v2019\Bookmark')->getBookmarkId($request);
    //print_r($v);
    $bookmarks = $v->getData()->data;
    $bookmark_array = explode(",",$bookmarks);
    $data = array();
    $resourceType="web";
    if ($request->has('resourceType') && $request->input('resourceType')!='')
		  $resourceType = $request->input('resourceType');
		  
    $data['memId'] = \App\Helper::getMemId();
    
	if (empty($data['memId']) && $request->has('memid') && $request->input('memid')!=''){
		//$data['memId'] = $request->input('memid');
			    $memid = htmlentities($request->input('memid'), ENT_QUOTES);

                if( !is_numeric($memid) ){
                    return response()->json([
                        'status' => [
                            "code" => 2001,
                            'message' => "Improper input values"
                        ]
                    ]);                    
                }
		$data['memId'] = $memid;
	}elseif (empty($data['memId']) && $request->has('accessToken') && $request->input('accessToken')!=''){
		$app_type='SM';
		if ($request->has('app_type') && $request->input('app_type')=='CM')
			$app_type='CM';
		$token = $request->input('accessToken');
		//$user = new User();
		$auth = new authentication();
		$user_id = $auth->authToken($token, $app_type);
		$data['memId'] = $user_id;
	}
	
    if ($request->has('pageValue') && $request->input('pageValue')!='')
		  $data["page"] = $request->input('pageValue');
		else 
		  $data["page"] = '';
		  
	if ($request->has('bookmarked') && $request->input('bookmarked')!='')
		  $is_bookmarked = $request->input('bookmarked');
		else 
		  $is_bookmarked = 0;
	 
	 $filter = array();
	 if ($request->has('filters'))
		$filter = $request->input('filters');
	
	$commCond = '';
    //if ($request->has('filters') && $request->input('filters')!=''){
    if ($request->has('app_type') && $request->input('app_type')=='CM'){
		$commCond = " and (commodityId = 401 or subCommodityId = 401 or subSubCommodityID = 401) and for_smgroup_company like '%coalmint.com%' ";
        $appType = 'CM';			
	}else{
      
	  $appType = 'SM';
	  $commCond = " and for_smgroup_company LIKE '%steelmint.com%'";
	}
	
	if(isset($filter['commodityID'])) {
		$commCond .= " AND (";
		$commCond .= " commodityID In ( " .  implode(',',$filter['commodityID']) .  ")";	
		$commCond .= " OR subCommodityID In ( " .  implode(',',$filter['commodityID']) .  ")";	
		$commCond .= " OR subSubCommodityID In ( " .  implode(',',$filter['commodityID']) .  ")";	
		$commCond .= ")";
	}
	
	if($request->has('commodityID') && $request->input('commodityID')!=0) {
		$commodityID =$request->input('commodityID');
		$commodityID = is_array($commodityID)?$commodityID:array($commodityID);
		$commCond .= " AND (";
		$commCond .= " commodityID In ( " .  implode(',',$commodityID) .  ")";	
		$commCond .= " OR subCommodityID In ( " .  implode(',',$commodityID) .  ")";	
		$commCond .= " OR subSubCommodityID In ( " .  implode(',',$commodityID) .  ")";	
		$commCond .= ")";
	}
	
    if($request->has('pageValue') && $request->input('pageValue')!=''){
          $pageValue = $request->input('pageValue');
          $offset = ($pageValue-1)*8;
    }else{ 
          $pageValue = 1;$offset=0;    
    }
    $validator = Validator::make($data, [
            'memId' => 'int'
    ]);      
    if ($validator->fails()) {
        $messages = $validator->messages();
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                'message' => $messages
            ]
        ]);
    }
    $sql = '';$cond='';
    $sql = "
		SELECT s.`post_id` AS itemID,
				(select itemName from tbl_region_commodity_master as cm where s.commodityId=cm.id and itemType='commodity') as commodityName,
			   s.`post_title` AS title,
			   s.`post_content` AS `description`,
			   s.`meta_description` AS metaDescription,
			   s.`post_tags` AS postTags,
			   s.slider_image AS `sliderImage`,
			   s.listing_image AS `listingImage`,
			   s.description_image AS descriptionImage,
			   s.`href`,
			   s.`f_excerpt`,
			   s.`created_at` AS publishDate,
			   r.`RM_name` AS `name`,
			   r.RM_email AS `email`,
			   r.`imageURL`,
			   r.`facebookId`,
			   r.`twitterId`,
			   s.author_name, s.author_id, s.author as author_email, f_tags
		FROM tbl_stats_infographics s
		LEFT JOIN tbl_rel_manager r ON s.author_id = r.id
		WHERE 1=1
		$commCond
	";
	

	
    if(isset($filter['type']) && isset($filter['type']) != null){
        switch($filter['type']){
            case "related":
               $cid = !empty($filter['itemID'])?$filter['itemID']:0;
               $sql .= " AND `commodityId` IN (SELECT `commodityId` from tbl_stats_infographics WHERE `post_id` = {$cid}) AND post_id<>{$cid}";
            break;
            case "description":
               $cid = !empty($filter['itemID'])?$filter['itemID']:0;
               $sql .= " AND s.`post_id` = {$cid}";
            break;
            default:
            break;
        }
    }

    if($data['memId']){
        $user = new User($data['memId'], $appType);
		$isAccessible =  $user->isAccessible($resourceType, $section='Infograph');
		
		if($isAccessible==-1){//post
		    if(!empty(Session::get('sectionFromDate'))){			
			    $sectionFromDate = Session::get('sectionFromDate');
		    
		    	//$sql .= " AND s.post_id not in (170611,170559,169704,169683) AND post_date >= '$sectionFromDate'";
		    	//removed post_date condition on 18-nov-2021 
		    	$sql .= " AND s.post_id not in (170611,170559,169704,169683) ";			
		    }else{
				$sql .= " AND post_date = '2001-01-01'";	
			}
		    
		   // $sql .= " AND `accessibleToPreLogin` = 'N' ORDER BY s.`id` DESC LIMIT {$offset},8 ";
		    //$sql .= " ORDER BY s.`id` DESC LIMIT {$offset},8 ";
		}
		else{//pre i.e. upgrade
			
			//$sql .= " AND `accessibleToPreLogin` = 'Y' ORDER BY s.`id` DESC LIMIT {$offset},4 "; 
		}
         
    } else {
        // $sql .= " AND `accessibleToPreLogin` = 'Y' ORDER BY s.`id` DESC LIMIT {$offset},4 "; 
		$isAccessible =0;
    }
    
    if($request->has('source') && $request->input('source')=='new_home'){
        $limit = 4;
		$offset = ($pageValue-1)*4;
    }elseif($request->has('source') && $request->input('source')=='app_stats_landing'){
        $limit = 10;
		$offset = ($pageValue-1)*10;
    }
    else
        $limit = 8;
    
    $sql .= " ORDER BY s.`id` DESC LIMIT {$offset},$limit "; 

		if((isset($filter['debug']) && $filter['debug'] == 1) || $data['memId']==56350000) {
            echo "<br /><br /><pre>1st sql:",$isAccessible, Session::get('userService'), print_r($request->all()), print_r($bookmark_array), "</pre>";
				
        } 		
    ///echo $sql;
    $rs = mysql_query($sql)or die(mysql_error().$sql);
    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)) {
  				
       $row["isBookmarked"] = in_array($row["itemID"],$bookmark_array)?"Y":"N";
         $row["itemID"] = intval($row["itemID"]);
         $row["title"] = stripslashes(html_entity_decode($row["title"], ENT_QUOTES));
		//Added condition to open all infographics in website as requested by Marcom - YKV 03rd Jan'23
		if ($resourceType == 'web')
			 $row["description"] = stripslashes(html_entity_decode($row["description"], ENT_QUOTES));
		else{
			if($isAccessible==-1 && Session::get('userService') != 'Standard' && Session::get('userService') != 'Price Only' && Session::get('userService') != 'Free Trial'){
			///$pageType='post'; 
			$row["description"] = stripslashes(html_entity_decode($row["description"], ENT_QUOTES));
			$row["description"] = str_replace("<p><p>", "", $row["description"]);
			$row["description"] = str_replace("</p></p>", "", $row["description"]);
			}else
			$row["description"] = 'hidden'; 
		}
		 
       ////  $row["description"] = stripslashes(html_entity_decode($row["description"], ENT_QUOTES));
         //$row["title"] = stripslashes(utf8_decode( html_entity_decode($row["title"], ENT_QUOTES)));
         //$row["href"] = str_replace("https://www.steelmint.com/insights","https://www.steelmint.com/statistics/infographic", $row["href"]);
         $row["href"] = "https://www.bigmint.co/infographic/detail/".$row["itemID"];
         //$row["description"] = stripslashes(utf8_decode(html_entity_decode($row["description"], ENT_QUOTES)));
         //$row["listingImage"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", $row["listingImage"]) . "?tr=w-255,h-203,dpr-2,cm-pad_resize";
		 $row["listingImage"] = $row["listingImage"] . "?tr=w-255,h-203,dpr-2,cm-pad_resize";
         
		 $row["authorDetails"]["authorID"] = intval($row['author_id']);
		 $row["authorDetails"]["name"] = $row["author_name"];
         $row["authorDetails"]["email"] = $row["author_email"];
         $row["authorDetails"]["imageUrl"] = $row["imageURL"];
         $row["authorDetails"]["socialAccounts"]["fb"] = $row["facebookId"];
         $row["authorDetails"]["socialAccounts"]["twitter"] = $row["twitterId"];
		 
         /* unset($row["name"]);
         unset($row["email"]);
         unset($row["imageURL"]);
         unset($row["facebookId"]);
         unset($row["twitterId"]); */
         
         if($is_bookmarked){
			if(in_array($row["itemID"],$bookmark_array)){
                $result[] = $row;
			}
		} else {
		    $result[] = $row;
		}    
    }
 		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($result), "</pre>";
				
        } 		
 
    return response()->json([
        'status' => [
            "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
            'message' => 'Success .'
        ],
        "data"=> $result
    ]);

  }
  
  //created for APP
  public function getInfographBM(Request $request){
    $result = array(); 
    $v = app('App\Http\Controllers\v2019\Bookmark')->getBookmarkId($request);
    //print_r($v);
    $bookmarks = $v->getData()->data;
    $bookmark_array = explode(",",$bookmarks);
    $data = array();
    $resourceType="web";
    if ($request->has('resourceType') && $request->input('resourceType')!='')
		  $resourceType = $request->input('resourceType');
		  
    $data['memId'] = \App\Helper::getMemId();
    
	if (empty($data['memId']) && $request->has('memid') && $request->input('memid')!=''){
		//$data['memId'] = $request->input('memid');
			    $memid = htmlentities($request->input('memid'), ENT_QUOTES);

                if( !is_numeric($memid) ){
                    return response()->json([
                        'status' => [
                            "code" => 2001,
                            'message' => "Improper input values"
                        ]
                    ]);                    
                }
		$data['memId'] = $memid;
	}elseif (empty($data['memId']) && $request->has('accessToken') && $request->input('accessToken')!=''){
		$app_type='SM';
		if ($request->has('app_type') && $request->input('app_type')=='CM')
			$app_type='CM';
		$token = $request->input('accessToken');
		//$user = new User();
		$auth = new authentication();
		$user_id = $auth->authToken($token, $app_type);
		$data['memId'] = $user_id;
	}
	
    if ($request->has('pageValue') && $request->input('pageValue')!='')
		  $data["page"] = $request->input('pageValue');
		else 
		  $data["page"] = '';
		  
	if ($request->has('bookmarked') && $request->input('bookmarked')!='')
		  $is_bookmarked = $request->input('bookmarked');
		else 
		  $is_bookmarked = 0;
	 
	 $filter = array();
	 if ($request->has('filters'))
		$filter = $request->input('filters');
	
	$commCond = '';
    //if ($request->has('filters') && $request->input('filters')!=''){
    if ($request->has('app_type') && $request->input('app_type')=='CM'){
		$commCond = " and (commodityId = 401 or subCommodityId = 401 or subSubCommodityID = 401) and for_smgroup_company like '%coalmint.com%' ";
        $appType = 'CM';			
	}else{
      
	  $appType = 'SM';
	  $commCond = " and for_smgroup_company LIKE '%steelmint.com%'";
	}
	
	if(isset($filter['commodityID'])) {
		$commCond .= " AND (";
		$commCond .= " commodityID In ( " .  implode(',',$filter['commodityID']) .  ")";	
		$commCond .= " OR subCommodityID In ( " .  implode(',',$filter['commodityID']) .  ")";	
		$commCond .= " OR subSubCommodityID In ( " .  implode(',',$filter['commodityID']) .  ")";	
		$commCond .= ")";
	}
	
	if($request->has('commodityID') && $request->input('commodityID')!=0) {
		$commodityID =$request->input('commodityID');
		$commodityID = is_array($commodityID)?$commodityID:array($commodityID);
		$commCond .= " AND (";
		$commCond .= " commodityID In ( " .  implode(',',$commodityID) .  ")";	
		$commCond .= " OR subCommodityID In ( " .  implode(',',$commodityID) .  ")";	
		$commCond .= " OR subSubCommodityID In ( " .  implode(',',$commodityID) .  ")";	
		$commCond .= ")";
	}
	
        //code added for App - market wise listing 
        if($request->has('selected_market') && !empty($request->input('selected_market')))
				$selected_market = $request->input('selected_market');
        
         if(!empty($filter['selected_market']) && empty($selected_market))
				$selected_market =$filter['selected_market'];

			
        if(!empty($selected_market)){
            $qry =  "select 
            GROUP_CONCAT(id) as commodities
            from tbl_region_commodity_master where FIND_IN_SET('".$selected_market."',f_market) and parentID=0 and itemtype='commodity' ";        
            $res = mysql_query($qry);
            $row = mysql_fetch_assoc($res);
            $market_commodities = $row['commodities'];
            $commCond .= " AND (";
                $commCond .= " commodityID IN (";
                $commCond .=     $market_commodities;
                $commCond .= ") OR ";
                $commCond .= " subCommodityID IN (";
                $commCond .=  $market_commodities;				
                $commCond .= ") OR ";
                $commCond .= " subSubCommodityID IN (";
                $commCond .=   $market_commodities;
                $commCond .= ")";
            $commCond .= ")";
        }
		
	
    if($request->has('pageValue') && $request->input('pageValue')!=''){
          $pageValue = $request->input('pageValue');
          $offset = ($pageValue-1)*8;
    }else{ 
          $pageValue = 1;$offset=0;    
    }
    $validator = Validator::make($data, [
            'memId' => 'int'
    ]);      
    if ($validator->fails()) {
        $messages = $validator->messages();
        return response()->json([
            'status' => [
                "code" => \App\RestApiResponseCodes::mandatoryParamsMissingCode,
                'message' => $messages
            ]
        ]);
    }
    $sql = '';$cond='';
    $sql = "
		SELECT s.`post_id` AS itemID,
				(select itemName from tbl_region_commodity_master as cm where s.commodityId=cm.id and itemType='commodity') as commodityName,
			   s.`post_title` AS title,
			   s.`post_content` AS `description`,
			   s.`meta_description` AS metaDescription,
			   s.`post_tags` AS postTags,
			   s.slider_image AS `sliderImage`,
			   s.listing_image AS `listingImage`,
			   s.description_image AS descriptionImage,
			   s.`href`,
			   s.`f_excerpt`,
			   s.`created_at` AS publishDate,
			   r.`RM_name` AS `name`,
			   r.RM_email AS `email`,
			   r.`imageURL`,
			   r.`facebookId`,
			   r.`twitterId`,
			   s.author_name, s.author_id, s.author as author_email, f_tags
		FROM tbl_stats_infographics s
		LEFT JOIN tbl_rel_manager r ON s.author_id = r.id
		WHERE 1=1
		$commCond
	";
	

	
    if(isset($filter['type']) && isset($filter['type']) != null){
        switch($filter['type']){
            case "related":
               $cid = !empty($filter['itemID'])?$filter['itemID']:0;
               $sql .= " AND `commodityId` IN (SELECT `commodityId` from tbl_stats_infographics WHERE `post_id` = {$cid}) AND post_id<>{$cid}";
            break;
            case "description":
               $cid = !empty($filter['itemID'])?$filter['itemID']:0;
               $sql .= " AND s.`post_id` = {$cid}";
               
               if(empty($selected_market) && $resourceType=='app' && !empty($data['memId'])){
                    $user = new User($data['memId'], $appType);
                    $selected_market =  $user->getMarketForAPPByItemID($resourceType,$cid,'infographics');                 
                }
         
            break;
            default:
            break;
        }
    }

    if($data['memId']){
        $user = new User($data['memId'], $appType);        
		//$isAccessible =  $user->isAccessible($resourceType, $section='Infograph');
		$isAccessible =  $user->isAccessible($resourceType, $section='Infograph', '', '', '', $selected_market);
		
		//handle blank selected_market case - showing only accessible infographs
		if(empty($selected_market) && $resourceType=='app' && !empty($data['memId'])){                
            $all_session = session()->all();
            $accessible_mkt = array_filter(explode(",",$all_session['marketsIncludes']));
            $infograph_mkt=array();
            $infograph_date = '';
            foreach($accessible_mkt as $key_mkt){
                $mergedArray = array_unique(explode(',', strtolower($all_session[$key_mkt]['sectionsIncludes'])));                   
                if(in_array('infograph',$mergedArray)){                                      
                    $infograph_mkt[] = $key_mkt;
                    if($infograph_date=='' || strtotime($infograph_date)>strtotime($all_session[$key_mkt]['sectionsIncludes']))
                        $infograph_date = $all_session[$key_mkt]['startdate'];
                }
            }
            if(!empty($infograph_mkt)){
                //as there is no restriction for date - we are not adding any condition for date wise
                $whr_arr=[];
                foreach($infograph_mkt as $inf_mkt){
                      $whr_arr[] = "FIND_IN_SET('".$inf_mkt."',f_market)";      
                }
                if(!empty($whr_arr)){
                    $whr_case = " and (" .implode(" OR ", $whr_arr).")";
                    $isAccessible=-1;
                     $qry =  "select 
                        GROUP_CONCAT(id) as commodities
                        from tbl_region_commodity_master where itemtype='commodity' $whr_case ";        
                        $res = mysql_query($qry);
                        $row = mysql_fetch_assoc($res);
                        $market_commodities = $row['commodities'];
                        if(empty($market_commodities)){
                            $sql .= " AND 0 ";
                        }else{
                        $sql .= " AND (";
                            $sql .= " commodityID IN (";
                            $sql .=     $market_commodities;
                            $sql .= ") OR ";
                            $sql .= " subCommodityID IN (";
                            $sql .=  $market_commodities;				
                            $sql .= ") OR ";
                            $sql .= " subSubCommodityID IN (";
                            $sql .=   $market_commodities;
                            $sql .= ")";
                        $sql .= ")";
                    }
                }
            }
        }
			
		if($isAccessible==-1){//post
		    if(!empty(Session::get($selected_market)['sectionFromDate']) || !empty($infograph_date)){			
			    $sectionFromDate = Session::get($selected_market)['sectionFromDate'];
		    
		    	//$sql .= " AND s.post_id not in (170611,170559,169704,169683) AND post_date >= '$sectionFromDate'";
		    	//removed post_date condition on 18-nov-2021 
		    	$sql .= " AND s.post_id not in (170611,170559,169704,169683) ";			
		    }else{
				$sql .= " AND post_date = '2001-01-01'";	
			}
		    
		   // $sql .= " AND `accessibleToPreLogin` = 'N' ORDER BY s.`id` DESC LIMIT {$offset},8 ";
		    //$sql .= " ORDER BY s.`id` DESC LIMIT {$offset},8 ";
		}
		else{//pre i.e. upgrade
			
			//$sql .= " AND `accessibleToPreLogin` = 'Y' ORDER BY s.`id` DESC LIMIT {$offset},4 "; 
		}
         
    } else {
        // $sql .= " AND `accessibleToPreLogin` = 'Y' ORDER BY s.`id` DESC LIMIT {$offset},4 "; 
		$isAccessible =0;
    }
    
    if($request->has('source') && $request->input('source')=='new_home'){
        $limit = 4;
		$offset = ($pageValue-1)*4;
    }elseif($request->has('source') && $request->input('source')=='app_stats_landing'){
        $limit = 10;
		$offset = ($pageValue-1)*10;
    }
    else
        $limit = 8;
    
    $sql .= " ORDER BY s.`id` DESC LIMIT {$offset},$limit "; 

		if((isset($filter['debug']) && $filter['debug'] == 1) || $data['memId']==56350000) {
            echo "<br /><br /><pre>1st sql:",$isAccessible."<br />". Session::get($selected_market)['userService'];
            echo "<br />";
            print_r(session()->all());
            echo "<br />"; 
            print_r($bookmark_array);
            echo "</pre>";
             echo $sql."-->";
             print_r($row);
				
        } 		
   
    $rs = mysql_query($sql)or die(mysql_error().$sql);
    while($row = mysql_fetch_array($rs,MYSQL_ASSOC)) {
  				
       $row["isBookmarked"] = in_array($row["itemID"],$bookmark_array)?"Y":"N";
         $row["itemID"] = intval($row["itemID"]);
         $row["title"] = stripslashes(html_entity_decode($row["title"], ENT_QUOTES));
		//Added condition to open all infographics in website as requested by Marcom - YKV 03rd Jan'23
		if ($resourceType == 'web')
			 $row["description"] = stripslashes(html_entity_decode($row["description"], ENT_QUOTES));
		else{
			if($isAccessible==-1 && Session::get($selected_market)['userService'] != 'Standard' && Session::get($selected_market)['userService'] != 'Price Only' && Session::get($selected_market)['userService'] != 'Free Trial'){
			///$pageType='post'; 
			$row["description"] = stripslashes(html_entity_decode($row["description"], ENT_QUOTES));
			$row["description"] = str_replace("<p><p>", "", $row["description"]);
			$row["description"] = str_replace("</p></p>", "", $row["description"]);
			}else
			$row["description"] = 'hidden'; 
		}
		 
       ////  $row["description"] = stripslashes(html_entity_decode($row["description"], ENT_QUOTES));
         //$row["title"] = stripslashes(utf8_decode( html_entity_decode($row["title"], ENT_QUOTES)));
         $row["href"] = str_replace("https://www.steelmint.com/insights","https://www.steelmint.com/statistics/infographic", $row["href"]);
         //$row["description"] = stripslashes(utf8_decode(html_entity_decode($row["description"], ENT_QUOTES)));
         //$row["listingImage"] = str_replace("https://www.steelmint.com","https://img.steelmint.com", $row["listingImage"]) . "?tr=w-255,h-203,dpr-2,cm-pad_resize";
		 $row["listingImage"] = $row["listingImage"] . "?tr=w-255,h-203,dpr-2,cm-pad_resize";
         
		 $row["authorDetails"]["authorID"] = intval($row['author_id']);
		 $row["authorDetails"]["name"] = $row["author_name"];
         $row["authorDetails"]["email"] = $row["author_email"];
         $row["authorDetails"]["imageUrl"] = $row["imageURL"];
         $row["authorDetails"]["socialAccounts"]["fb"] = $row["facebookId"];
         $row["authorDetails"]["socialAccounts"]["twitter"] = $row["twitterId"];
		 
         /* unset($row["name"]);
         unset($row["email"]);
         unset($row["imageURL"]);
         unset($row["facebookId"]);
         unset($row["twitterId"]); */
         
         if($is_bookmarked){
			if(in_array($row["itemID"],$bookmark_array)){
                $result[] = $row;
			}
		} else {
		    $result[] = $row;
		}    
    }
 		if(isset($filter['debug']) && $filter['debug'] == 1) {
            echo "<pre>", print_r($result), "</pre>";
				
        } 		
 
    return response()->json([
        'status' => [
            "code" => \App\RestApiResponseCodes::RequestSentSuccessfullyCode,
            'message' => 'Success .'
        ],
        "data"=> $result
    ]);

  }


}



?>
