<?php
/**
 * Created by PhpStorm.
 * User: varun
 * Date: 21/11/15
 * Time: 6:54 PM
 */

namespace App\Http\Controllers;

use App\Http\Controllers\Auth\User ;

use App\Http\Controllers\Action\News;


use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Auth\authentication;

use App\Http\Controllers\Controller;

use DB;

use DateTime;
use DateTimeZone;
use Symfony\Component\HttpFoundation\Response;

use App\Http\Controllers\Action\Common ;
/**
 * Class NewsController: for news
 * @package App\Http\Controllers
 */
class NewsController extends Controller
{
    private $debug = false;
    private $latest_id = NULL;
	
/*  ================= START =============:  new funcitons fetching data from new table tbl_news_post */
    private $newsRegions = [
        "India"             =>  "India",
        "China"       =>  "China",
        "Japan, Korea"             =>  "asia",
        "Pakistan, Bangladesh, Nepal"        =>  "asia",
        "Australia"   =>  "europe, us and asia pacific",
        "South East Asia"               =>  "europe, us and asia pacific",
        "Middle East Africa"              =>  "MENA",
        "CIS Nations"            =>  "europe, us and asia pacific",  
        "Europe"          =>  "europe, us and asia pacific",
        "US/Canada"          =>  "europe, us and asia pacific",
        "Brazil"          =>  "europe, us and asia pacific",
        "Global"          =>  "europe, us and asia pacific"
    ];

    public function __construct(Request $request) {
        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;
        }
        /** Added by shreetam on 9jan2019**/
         $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/data.json"), true);
        if($fotomineImages) {
            $this->latest_id = $fotomineImages['id'];
        }
    }

	public function get_news_filters(Request $request)
   {
       $filters = array();

       $path = storage_path() . "/json/news_portfolio_category.json";
       $file_content = json_decode(file_get_contents($path), true);

       if(isset($file_content['filters']) && !empty($file_content['filters'])) {
           $filters = $file_content['filters'];
       }

       return new JsonResponse(array ("status#" => "1" , "data#" => array_values($filters)));
   }
   public function get_all_news_categories(Request $request)
   {
       $categories = array();

       $path = storage_path() . "/json/news_portfolio_category.json";
       $categories_content = json_decode(file_get_contents($path), true);

       if(isset($categories_content['categories']) && !empty($categories_content['categories'])) {
           $categories = $categories_content['categories'];
       }

       $latest_news_regions = array();
       $latest_news_regions['regions'] = [
	   
			"asia"	=> "Asia",
			"mena"	=>"MENA",
			"europe, us and asia pacific"	=>"Europe, US and Asia Pacific",
			"india"	=>"India",
			"china"	=>"China"	,
			"bangladesh"	=>"Bangladesh"
			/*"Middle East and Africa"	=>	"Middle East and Africa",
"US/Canada"	=>	"US/Canada",
"UK/Europe/Brazil"		=> "UK/Europe/Brazil",
"India"	=>	"India",
"China"	=>	"China",
"Pakistan/Bangladesh/Nepal/Sri Lanka"	=>	"Pakistan/Bangladesh/Nepal/Sri Lanka",
"Australia"	=>	"Australia",
"Japan/Korea/Taiwan"	=>	"Japan/Korea/Taiwan"*/

        ];

       return new JsonResponse(array ("status#" => "1" , "data#" => array_values($categories), "latest_news_regions#" => array_values($latest_news_regions)));
   }
   
	public function get_news_by_id(Request $request, $id)
    {
		include_once "/home/steelmin/public_html/inc/config1.php";	
    	include_once('/home/steelmin/public_html/hf.php');

        $userAccess = 1;
        $web_domain = 'steelmint.com';
		$appType='SM';
		if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){
			$web_domain = 'coalmint.com';
			$appType=strtoupper($request->input('appType'));
		}

        if ($request->has('token')) {
            $auth = new authentication();
            $token = $request->input('token');
            $user_id = $auth->authToken($token);
            if ($user_id) {
                $us = new User($user_id, $appType);
                $userAccess = $us->getTakenServicesByUser();
            } else {
                //abort(403, 'Unauthorized action. Token access denied');
                return new JsonResponse(array("status#" => "403" , "data#" => 'Unauthorized action. Token access denied'));			
            }
        }

        $newsFilter = array();
        $newsFilter['src'] = 'app';
        $newsFilter['post_id'] = $id;
		$newsFilter['language']='';
		
		if ($request->has('language')){
			$language = $request->input('language');
			$newsFilter['language'] = $language;			
		}
		if ($request->has('debug')){
			$newsFilter['debug']=$request->input('debug');
		}
		
		$result = array();
		$result = get_news_details($newsFilter, $web_domain, 0, $userAccess);

        // $posts = array();
        // if($result) {
        // 	$posts = $this->getFormatedNewsData($result, $userAccess, $web_domain, $request);
        // }
		include_once "/home/steelmin/public_html/inc/desconfig.php";	
        if($request->has('memid')) {
        	return new JsonResponse($result) ;
		} else {
        	return new JsonResponse(array("status#" => "1" , "data#" => $result));			
        }
    }

    public function updateMostread(Request $request)
    {

        if($request->has('token')) {
            $auth = new authentication();
            $token = $request->input('token');
            $user_id = $auth->authToken($token);
            if ($user_id) {
                $us = new User($user_id);
                $userAccess = $us->getTakenServicesByUser();
            } else {
                abort(403, 'Unauthorized action. Token access denied');
            }

            $post_id = 0;
            $count = 1;

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

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

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

            DB::statement($sql);

            return new JsonResponse(array(
                "status#"       => "1" ,
                "message#"      => "Updated successfully!"
            ));

        } else {
            abort(403, 'Unauthorized action. Token access denied');
        }
    }
   /* Added by shreetam date:  9 jan 2019 */ 
   public function views_count(){
            include_once "/home/steelmin/public_html/inc/config1.php";	
    	    include_once('/home/steelmin/public_html/hf.php');
            $views = get_views_count($this->latest_id);
            return new JsonResponse(array("status#" => "1" , "views#" => $views));
    }

    public function views_counter(){
                $sql = "UPDATE `fotomine_posts` SET `views` = (`views` + 1) WHERE `id` = " . (int)$this->latest_id;
                DB::statement($sql);    
                return new JsonResponse(array("status#" => "1" , "data#" => 'Success'));			
        
    }
   /* Added by shreetam date:  9 jan 2019  END ---- */ 
	public function get_all_news(Request $request)
    {
		//echo "begin"; 
         /*  if($this->debug == true) {
            print_r($request->all());
         }  */
        
        //return $request->all();
        include_once "/home/steelmin/public_html/inc/config1.php";  
        include_once('/home/steelmin/public_html/hf.php');

        $newsFilter = array(); // Used to create filter array for News function
        $filter = array(); // Used to get the request filter

        if($this->debug == true) {
            $newsFilter['debug'] = true;
        }

        $results = array();

        $newsFilter['src'] = 'app';

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

        $userAccess = 1;
        $web_domain = 'steelmint.com';
		$appType='SM';
		if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){
			$web_domain = 'coalmint.com';
			$appType=strtoupper($request->input('appType'));
		}
		
        if($request->has('token') || $request->has('memid')) { //user is logged in
            if($request->has('memid')) {
                $memid = $request->input('memid');
                $memid = _encrypt_decrypt($action='decrypt', $memid);
                $auth = new authentication();
                $user_id = $auth->authUserId($memid);//for web user
                
                $newsFilter['src'] = 'web';
                $newsFilter['forWebListing'] = true;
            } else {            
                $auth = new authentication();
                $token = $request->input('token');
                $user_id = $auth->authToken($token);
            }
            if ($user_id) {
                $us = new User($user_id, $appType);
                $userAccess = $us->getTakenServicesByUser();
            } else {
                return new JsonResponse(array(
                    "status#" => "403",
                    "message#" => "Unauthorized action. Token access denied"
                )) ;
            }
        }
        
        $start = 0 ;
        $number_of_posts = 30 ;
        if($request->has('memid')) {
            $number_of_posts = 10;
        }

        $filter = '';
        $category = '' ;
        $_app_post = '';

        /**
         * For retrive only updated news
         */
        if($request->has('postfrom')) {
            $newsFilter['postfrom'] = $request->input('postfrom');
            $_app_post = $request->input('postfrom') ;
        }

        /*
         * For start limit
         */
        if($request->has('start')) {
            $newsFilter['start'] = $request->input('start');
            $start = $request->input('start');
        } else {
            $newsFilter['start'] =  $start;
        }

        /*
         * Number of posts wants to see
         */
        if($request->has('number')) {
            $newsFilter['limit'] = $request->input('number');
            $number_of_posts = $request->input('number') ;
        } else {
            $newsFilter['limit'] =  $number_of_posts;
        }

        /*
         * For getting filter type
         */
        if($request->has('filter')) {
            if(!is_array($request->input('filter'))) { // For Generic Search
            
                $newsFilter['query'] = $request->input('filter');

                $results = get_news_details($newsFilter, $web_domain, 0, $userAccess);

                // $posts = array();
                // if($results) {
                //  $posts = $this->getFormatedNewsData($results, $userAccess, $web_domain, $request);
                // }

                return new JsonResponse(array("status#" => "1" , "data#" => $results));

            } else {
                $filter = $request->input('filter');
            }
        } else {
            /*
             * For getting category type
             */
            if($request->has('section_wise') && $request->input('section_wise') == true) {
                $requestedCategory = $request->input('category');

                if($requestedCategory) {
                    $newsFilter['categories'] = $requestedCategory;
                }

                 $requestedRegions = $request->input('regions');
                $requestedRegions = str_replace(", us ", " us ", strtolower($requestedRegions));
                
                /* if($request->has('debug')) {
                    dd ($requestedRegions);
                } */
                $requestedRegions = explode(",", $requestedRegions);
                $newsFilter['limit'] = $number_of_posts;
                if($request->has('snapshot') && $request->input('snapshot') == "true") {
                    $newsFilter['limit'] = 5;
                }
                
                $posts = array();
                
                if($requestedRegions) {
                    foreach($requestedRegions as $requestedRegion) {
                        //if(isset($this->newsRegions[strtolower($requestedRegion)])) {
                        $requestedRegion = str_replace(" us ", ", us ", strtolower($requestedRegion));
                        $results = array();
                        $newsFilter['regions'] = $requestedRegion;
                        $results = get_news_details($newsFilter, $web_domain, 0, $userAccess);

                        if($results) {
                            // if($request->has('snapshot') && $request->input('snapshot') == "true") {
                                //$posts[ucwords(strtolower($requestedRegion))] = $this->getFormatedNewsData($results, $userAccess, $web_domain, $request);
                                $posts[ucwords(strtolower($requestedRegion))] = $results;
                            // } else {
                            //     $posts = $this->getFormatedNewsData($results, $userAccess, $web_domain, $request);
                            // }
                        }
                        //}
                    }
                }

                return new JsonResponse(array("status#" => "1" , "data#" => $posts));

            } else if($request->has('category')) {
                $newsFilter['categories'] = $request->input('category');
                $results = get_news_details($newsFilter, $web_domain, 0, $userAccess);

                
/*
    start: code to append fotomine data if requested only for main listing under each tab
*/  $images = [];
                //if($this->debug == true)
                if($newsFilter['categories'] != ''){
            
                    /* switch($newsFilter['categories']){
                         case "Iron Ore":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_iron.json"), true);     
                         break;
                         case "Semi Finished":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_semi_finished.json"), true);
                         break;
                         case "Coal":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_coal.json"), true);
                         break;
                         case "Scrap":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_scrap.json"), true);
                         break;
                         case "Finish Flat":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_flat.json"), true);
                         break;
                         case "Ferro Alloy":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_ferro.json"), true);
                         break;
                         case "others":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_others.json"), true);
                         break;
                    
                    } */
                
                
                } else {
                    //$fotomineImages = json_decode(file_get_contents("http://www.theitbooth.com/fotomine/api/public/?category=" . urlencode($newsFilter['categories'])), true);
                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/data.json"), true);        
                }    
                
                {
                
                if($fotomineImages) {
                        //foreach($fotomineImages as $image) {
                        foreach($fotomineImages['data#'] as $image) {
                            if($image['type'] == 'V' || $image['type'] == 'v'){
                                $exp = explode('v=',$image['path']);
                                $id = $exp[1];
                                $hq_def = "https://img.youtube.com/vi/".$id."/hqdefault.jpg";                   
                            }
                            else {
                                $exp = explode('images/',$image['path']);
                                $id = explode('/',$exp[1]);
                                //$img_thumb = "https://www.steelmint.com/fotomine/api/public/fotomine/images/mobile/".$id[1];
                                $img_thumb = "https://www.steelmint.com/fotomine/api/public/fotomine/images/slider/".$id[1];
                            }
                            /*$images[] = [
                                'image'     =>  ($image['type'] == 'I' || $image['type'] == 'i') ? $image['path'] :$hq_def,
                                'video'     =>  ($image['type'] == 'V' || $image['type'] == 'v') ? $image['path'] : ''
                            ];*/
                            $images[] = [
                                'title'     =>   $image['title'],
                                'desc'      =>   $image['desc'],
                                'thumb'     =>   ($image['type'] == 'I' || $image['type'] == 'i') ? $img_thumb :$hq_def,
                                'image'     =>   $image['path'],
                                'video'     =>   ($image['type'] == 'V' || $image['type'] == 'v') ? $image['path'] : '',
                                'shareUrl'     =>   'https://www.steelmint.com/gallery.html'
                            ];
                        }
                    }   
                    return new JsonResponse(array("status#" => "1" , "data#" => $results, "Image_Video_Data" => $images));      
                
                }
/*
    end: code to append fotomine data if requested only for main listing under each tab
*/      
                
    /*  if($this->debug == true)
        {
            echo "just b4 return<pre>";
            print_r($results);
            dd();
        }   
                 */
                return new JsonResponse(array("status#" => "1" , "data#" => $results));
            } else if($request->has('sub_category')) {
                // Mapping of Price Category and News Category goes here
                $category = '';
                $newsFilter['sub_categories'] = strtolower($request->input('sub_category'));
           }        
        }
        
        /*portfolio filter*/
        if($request->has('portfolio')) {
           $common = new Common();
            $temp = $common->getUserPortfolio($user_id, 'news', $appType);
            
            if(empty($temp['category']) && empty($temp['country'])){
                $posts = array();
                return new JsonResponse( array("status#" => "1" , "data#" =>$posts));
                //return new JsonResponse( $posts);
            }

            $category_id = $temp['category'];
            $category_id = rtrim($category_id, ",");
            //$category_ids = explode(",", $category_id);
            $category = array();

            /*if( strpos($category_id, '13') !== false || strpos($category_id, '16') !== false || strpos($category_id, '17') !== false  || strpos($category_id, '114') !== false  )
                $category[] = "RAW MATERIAL";*/
            if( strpos($category_id, '13') !== false   )
                $category[] = "Iron Ore";
             if( strpos($category_id, '16') !== false   )
                $category[] = "Coal";   
            if( strpos($category_id, '17') !== false   )
                $category[] = "Scrap,Ferrous Scrap";     
            if( strpos($category_id, '18') !== false  )
                $category[] = "SEMI FINISHED";
            if( strpos($category_id, '22') !== false  )
                $category[] = "FERRO ALLOY";
            if( strpos($category_id, '24') !== false   )
                $category[] = "FINISH FLAT";
            if( strpos($category_id, '25') !== false  )
                $category[] = "FINISH LONG";
                
            $path = storage_path() . "/json/news_portfolio_category.json";
            $categories = json_decode(file_get_contents($path), true);
            $raw_material_alt = array(13, 14, 15, 16);
            $newsFilter['categories'] = implode(",", array_values(array_unique($category)));
            $country = rtrim($temp['country'], ";");
            $countries = explode(";", $country);

            $regions = array();
            if($countries) {
                foreach($countries as $country) {
                    $regions[] = trim($country);
                }
            }

            $newsFilter['regions'] = implode(",", $regions);
            
        }///*end portfolio filter*/

        if(isset($filter['mostread'])) {
            $newsFilter['sort'] = 'n.`most_read`';
            $newsFilter['order'] = 'DESC';
        }

        /**
         * For region wise filter
         */
        if(isset($filter['country'])) {
            $newsFilter['regions'] = str_replace(";", ",", $filter['country']);
        } else if(isset($filter['regions'])) {
            $newsFilter['regions'] = str_replace(";", ",", $filter['regions']);
        }
        //print_r ($filter); die;
        if(isset($filter['categories'])) {
            $newsFilter['categories'] = str_replace(";", ",", $filter['categories']);           
        }
        
        /* if($this->debug == true)
        {
            echo "just b4 return - latest news<pre>";
            print_r($newsFilter);
            print_r($filter);
            print_r($request->all());
            dd();
        }    */
        
        $results = get_news_details($newsFilter, $web_domain, 0, $userAccess);

        include_once "/home/steelmin/public_html/inc/desconfig.php";    $images = [];
/*
    start: code to append fotomine data if requested only for main listing under each tab
*/  
        //if($this->debug == true)
        /*if($newsFilter['categories'] != ''){
            $images = [];
            //$fotomineImages = json_decode(file_get_contents("http://www.theitbooth.com/fotomine/api/public/?category=" . urlencode($newsFilter['categories'])), true);
            $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data.json"), true)
            if($fotomineImages) {
                //foreach($fotomineImages as $image) {
                foreach($fotomineImages['data#'] as $image) {
                  if($image['type'] == 'V' || $image['type'] == 'v'){
                                $exp = explode('v=',$image['path']);
                                $id = $exp[1];
                                $hq_def = "https://img.youtube.com/vi/".$id."/hqdefault.jpg";                   
                            }
                    if($newsFilter['categories'] != "Scrap"){       
                    $images[] = [
                        'image'     =>  ($image['type'] == 'I' || $image['type'] == 'i') ? $image['path'] : $hq_def,
                        'video'     =>  ($image['type'] == 'V' || $image['type'] == 'v') ? $image['path'] : ''
                    ];
                    } else {
                    $images=[]; 
                    }
                }
            }   
            return new JsonResponse(array("status#" => "1" , "data#" => $results, "Image_Video_Data" => $images));  
          } else*/
          
          
          
          if($newsFilter['categories'] != ''){
            
                    /* switch($newsFilter['categories']){
                         case "Iron Ore":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_iron.json"), true);     
                         break;
                         case "Semi Finished":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_semi_finished.json"), true);
                         break;
                         case "Coal":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_coal.json"), true);
                         break;
                         case "Scrap":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_scrap.json"), true);
                         break;
                         case "Finish Flat":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_flat.json"), true);
                         break;
                         case "Ferro Alloy":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_ferro.json"), true);
                         break;
                         case "others":
                                    $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/api/public/fotomine/data_others.json"), true);
                         break;
                    
                    } */

                }  else  {            
            $fotomineImages = json_decode(file_get_contents("/home/steelmin/public_html/fotomine/data.json"), true);
            }
            {
            if($fotomineImages) {
                foreach($fotomineImages['data#'] as $image) {
                  if($image['type'] == 'V' || $image['type'] == 'v'){
                                $exp = explode('v=',$image['path']);
                                $id = $exp[1];
                                $hq_def = "https://img.youtube.com/vi/".$id."/hqdefault.jpg";                   
                            }
                            else {
                                $exp = explode('images/',$image['path']);
                                $id = explode('/',$exp[1]);
                                //$img_thumb = "https://www.steelmint.com/fotomine/api/public/fotomine/images/mobile/".$id[1];
                                $img_thumb = "https://www.steelmint.com/fotomine/api/public/fotomine/images/slider/".$id[1];
                            }
                            
                            
                            /*$images[] = [
                                'image'     =>  ($image['type'] == 'I' || $image['type'] == 'i') ? $image['path'] : $hq_def,
                                'video'     =>  ($image['type'] == 'V' || $image['type'] == 'v') ? $image['path'] : ''
                            ];*/
                            $images[] = [
                                        'title'     =>   $image['title'],
                                        'desc'      =>   $image['desc'],
                                        'thumb'     =>   ($image['type'] == 'I' || $image['type'] == 'i') ? $img_thumb :$hq_def,
                                        'image'     =>   $image['path'],
                                        'video'     =>   ($image['type'] == 'V' || $image['type'] == 'v') ? $image['path'] : '',
                                        'shareUrl'     =>   'https://www.steelmint.com/gallery.html'
                                    ];
                         
                }
            }   
            return new JsonResponse(array("status#" => "1" , "data#" => $results, "Image_Video_Data" => $images));  
        }    
 
/*
    end: code to append fotomine data if requested only for main listing under each tab
*/      
 
//        return new JsonResponse(array("status#" => "1" , "data#" => $results));
    }

    public function getFormatedNewsData($posts = array(), $userAccess = 1, $web_domain = '', $request)
    {
    	
        $allData = array();
    	if($posts) {
    		foreach($posts as $post) {
    			$title = strip_tags(htmlspecialchars_decode($post['post_title'], ENT_QUOTES));

                //$post_date = date('M d, Y H:i', strtotime($post['post_date'] . " " . $post['post_time'] . " +5 hours 30 minutes") );
                $post_date = date('M d, Y H:i', strtotime($post['post_date'] . " " . $post['post_time']) );
                
                //$posted_on = $this->_timeSince($post_date);
                $posted_on = $this->_timeSince(date('M d, Y H:i', strtotime($post['post_date'] . " " . $post['post_time'] . " +5 hours 30 minutes") ));
                $post_modified = $posted_on;

                $content = $post['post_content'];
                $user_type = '';
				//$content_before_table  = ''; $content_after_table = ''; $content_of_table = '';
                if(!$request->has('memid')) {
                	if($userAccess == -1) {
                		$breaks = array("\n", "\r");
						$content = str_replace($breaks, " ", $content);
						$user_type = 'paid';
						
						/* if( strpos($content, "<table") !== false ){
							$pos_start = strpos($content, "<table");
							$content_before_table = substr($content, 0, $pos_start);

							$pos_end = strpos($content, "</table>");
							$content_after_table = substr($content, $pos_end+8, strlen($content) - 1);

							$content_of_table = substr($content, $pos_start, $pos_end - $pos_start + 8);
						}	 */
                	} else if($userAccess == 1) {
                        $content = strip_tags(htmlspecialchars_decode($content, ENT_QUOTES));
						$content = substr($content, 0, 100) . '<SM>...Login';
						
						$breaks = array("\r\n", "\n", "\r");
						$content = str_replace($breaks, " ", $content);
						$user_type = 'login';
                	} else {
                        $content = strip_tags(htmlspecialchars_decode($content, ENT_QUOTES));
						$content = substr($content, 0, 200) . '<SM>...Upgrade';
						
						$breaks = array("\r\n", "\n", "\r");
						$content = str_replace($breaks, " ", $content);
						$user_type = 'upgrade';
                	}
                } else {
					$content = stripslashes(strip_tags(html_entity_decode($content)));
					$maxlength = 150;
					$short_description = substr($content, 0, ($spos = strpos($content, '.', $lcount = count($content) > $maxlength ? $lcount : $maxlength)) ? $spos : $lcount ).'.';
					
					$breaks = array("\r\n", "\n", "\r");
					$content = str_replace($breaks, " ", $short_description);
                }

                $href = str_replace('https://news.steelmint.com', 'news', rtrim($post['href'],'/'));
                $href = str_replace('/news/', '/news/', $href);

                if($web_domain != '' && strpos($web_domain, "steelmint.com") === false){
                    $href= str_replace('https://www.steelmint.com/news/', $web_domain, $href);
                }

                $medium_image = $post['medium_image'];
                $thumb_image = $post['image'];

                $category = $post['category'];
                $sub_category = $post['sub_category'];
                if(empty($sub_category)) {
                	$sub_category = 'UNCATEGORIZED';
                }

                /*$results[] = array(
                	'ID'			=>	$post['post_id'],
                	'post_title'	=>	html_entity_decode($title, ENT_QUOTES),
                	'post_content'	=>	html_entity_decode($content, ENT_QUOTES),
                	'category'		=>	$category,
                	'sub_category'	=>	$sub_category,
                	'author_name'	=>	$post['author_name'],
                	'href'			=>	$href,
                	'image'			=>	$post['image'],
                	'medium_image'	=>	$post['medium_image'],
                	'post_date'		=>	$post_date,
                	'posted_on'		=>	$posted_on,
                	'post_modified'	=>	$post_date,
                	'user_type'		=>	$user_type,
                );*/
				//include_once "/home/steelmin/public_html/hf.php";
				//$href= get_bitly_short_url($href, "steelmint","R_2787014e7b7e637126071abdef182d73" ) ;
                $results['ID'] = strval($post['post_id']);
                $results['post_title'] = html_entity_decode($title, ENT_QUOTES);
                $results['post_content'] = html_entity_decode($content, ENT_QUOTES);
                $results['sub_category'] = $sub_category;
				$results['category'] = $category;
                $results['author_name'] = $post['author_name'];
                $results['href'] = $href;
                $results['image'] = $post['image'];
                $results['medium_image'] = $post['medium_image'];
                $results['post_date'] = $post_date;
                $results['posted_on'] = $post_date;
                $results['post_modified'] = $post_date;
                $results['user_type'] = $user_type;
                $results['most_read'] = $post['most_read'];
                $allData[] = $results;
    		}
    	}

    	return $allData;
    }

    public function _timeSince($from) {
        date_default_timezone_set("Asia/Kolkata");

        $seconds = time() - strtotime($from);

        $secondsInAMinute = 60;
        $secondsInAnHour = 60 * $secondsInAMinute;
        $secondsInADay = 24 * $secondsInAnHour;

        $days = floor($seconds / $secondsInADay);

        $hourSeconds = $seconds % $secondsInADay;
        $hours = floor($hourSeconds / $secondsInAnHour);

        $minuteSeconds = $hourSeconds % $secondsInAnHour;
        $minutes = floor($minuteSeconds / $secondsInAMinute);

        $remainingSeconds = $minuteSeconds % $secondsInAMinute;
        $seconds = ceil($remainingSeconds);

        $timeParts = [];
        $sections = [
            'day'   => (int)$days,
            'hour'  => (int)$hours,
            'min'   => (int)$minutes,
            'sec'   => (int)$seconds,
        ];

        foreach ($sections as $key => $value){
            if ($value > 0){
                $timeParts[] = $value . ' ' . $key . ($value == 1 ? '' : 's');
            }
        }

        if($timeParts) {
            return implode(' ', array_slice($timeParts, 0, 2));
        } else {
            return '1 sec';
        }
    }
/*  ================= END =============:  new funcitons fetching data from new table tbl_news_post */
	
	
	function getWPNewsCountry(){
		//require_once('/home/steelmin/public_html/news/wp-blog-header.php');
		$field_key = "country";
		$field = get_field_object($field_key);
		$res=array();
		if( $field )
		{
			foreach( $field['choices'] as $k => $v )
			{
				$res[$k]=$v;
			}
		}

		/*
		Array
		(
			[asia] => ASIA (BHUTAN,INDONESIA,JAPAN,KOREA,BANGLADESH,CHINA,INDIA,PAKISTAN,TAIWAN)
			[mena] => MENA (AUSTRALIA,BRAZIL,RUSSIA,UKRAINE,US EAST COAST,ALBANIA,EUROPE,TURKEY)
			[europe, us and asia pacific] => EUROPE, US And ASIA PACIFIC (IRAN,OMAN,GABON,GHANA,SOUTH AFRICA,ABU DHABI,DUBAI,MIDDLE EAST)
			[india] => India
			[china] => China
			[bangladesh] => Bangladesh
		)
		*/
		return json_encode($res);
	}


    /**
     * Get all filters for news
     * @param Request $request
     *
     */
    public function getfiltersNew(Request $request){
		// $common = new Common();
		
		// $filters['mostread'] = 'mostread';	
		// $filters['categories'] = $common->getNewCategories('news_arr');	
		// $filters['regions'] = $common->getRegions('news_arr');
		
		// return new JsonResponse(array ( "status#" => "1" , "data#" => $filters) ) ;

        $path = storage_path() . "/json/constants/v2_action_news_filtersnews.json";
        $filter = json_decode(file_get_contents($path), true);

        return new JsonResponse($filter);
	}
	
    public function getfilters(Request $request)
    {
		require_once('/home/steelmin/public_html/news/wp-blog-header.php');
		require_once "/home/steelmin/public_html/hf.php"; 
		$finalCountryArr = $unformatedArr = $countryArr = array();
		$countryJson = '';
		$countryJson = getWPNewsCountry();
		$countryArr = (array) json_decode($countryJson);
		
		if(isset($countryArr) && !empty($countryArr)) {
			foreach($countryArr as $key=>$unformatedStr) {
				//$unformatedArr = array_map('trim',str_replace(array("ASIA","MENA","(",")"),'',explode(",",$unformatedStr)));
				//foreach($unformatedArr as $cleanCountryValues)
				//{
					//$finalCountryArr[] = array("filter" => $cleanCountryValues);
				//}
				$finalCountryArr[] = array("filter" => ucwords($key));
			}
		}
		sort($finalCountryArr);
		//echo "<pre>";print_r($finalCountryArr);


        $filters[] = array ( 'filter' => "mostread"  ) ;
        $filters[] = array ( 'filter' => "country" , "sub_filter" => $finalCountryArr ) ;

//        $filters[] = array(
//            "filter" => "Region Wise" ,
//            "sub_filter" => [
//                "filter" => explode( ',' , file_get_contents("https://www.steelmint.com/news/company_list.txt") )
//            ]
//        ) ;

        return new JsonResponse(array ( "status#" => "1" , "data#" => $filters) ) ;
    }

    /*
     * Get all categories of news at one time
     */
    public function getcategory(Request $request)
    {
        /*
         * Making argument to query to wordpress for asking all categories
         */
        $args = array(
            'orderby' => 'id',
            'order' => 'ASC',
            'parent' => 0,
            'hide_empty' => 0,
            'hierarchical' => 1,
        );
        $res_arr = array();
        /*
         * Wordpress function calling
         */
        $categories = get_categories($args);
        /*
         * Loop to iterate categories and store in an array
         */
        foreach($categories as $k=>$category)
        {
            if($category->cat_ID < 550){
                $res_sub_array = array();
                foreach( get_categories( array ( 'child_of' => $category->cat_ID) ) as $j=>$sub_cat)
                {
                    $res_sub_array[] = array(
                        'cat_id' => $sub_cat->cat_ID,
                        'cat_name'=> $sub_cat->cat_name
                    );
                }
                if(  strcasecmp($category->cat_name , 'UNCATEGORIZED' ) != 0  )
                    $res_arr[$k] = array(
                        'cat_id'=> $category->cat_ID,
                        'cat_name'=> $category->cat_name,
                        'sub_cat' => $res_sub_array
                    );
            }
        }
        return new JsonResponse (array ( "status#" => "1" , "data#" => array_values($res_arr) ) ) ;
    }


    public function getnewsByid(Request $request, $id )
    {
        $userAccess = 0;
        $web_domain = 'steelmint.com';
        $posts = array();

        if ($request->has('token'))
        {
            $auth = new authentication();
            $token = $request->input('token');
            $user_id = $auth->authToken($token);
            if ($user_id) {
                $us = new User($user_id);
                $userAccess = $us->getTakenServicesByUser();
//                var_dump($userAccess) ;
            } else
                abort(403, 'Unauthorized action. Token access denied');
        } else {//user is NOT logged in
		        $userAccess = 1;
		}

        $posts = $this->query_result("p=$id" , $userAccess , $web_domain, $request ) ;

        return new JsonResponse( array ( "status#" => "1" , "data#" => $posts) );
    }

    /*
     * Get list of all news
     */
    public function getallnews(Request $request)
    {
		
		if( $request->has('token')  ){
			 $token = $request->input('token');
		}
		
		
        $userAccess = 0;
        $web_domain = 'steelmint.com';
        $posts = array();
        $wordpress_prifix = $_ENV['DB_WORDPRESS_TABLE_PREFIX'] ;
		
		$appType='SM';
		if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){
			$web_domain = 'coalmint.com';
			$appType=strtoupper($request->input('appType'));
		}
		
		//visitor => 1
		//upgarde => 0
		//value => -1
		

       if($request->has('token') || $request->has('memid')
             ) //user is logged in
        {
            if($request->has('memid')){
				$memid = $request->input('memid');
				$memid = _encrypt_decrypt($action='decrypt', $memid);
				$auth = new authentication();
				$user_id = $auth->authUserId($memid);//for web user
			}else{			
				$auth = new authentication();
				$token = $request->input('token');
				$user_id = $auth->authToken($token);
			}
            if ($user_id) {
                $us = new User($user_id, $appType);
                $userAccess = $us->getTakenServicesByUser();
//                var_dump($userAccess) ;
            } else{
			 return new JsonResponse(array(
                    "status#" => "403" ,
                    "message#" => "Unauthorized action. Token access denied"
                )) ;
              //  abort(403, 'Unauthorized action. Token access denied');
			}

        } else {//user is NOT logged in
		        $userAccess = 1;
		}

        $start = 0 ;
        $number_of_posts = 50 ;
if($request->has('memid'))
	$number_of_posts = 10 ;

        $filter=''; $category='' ;
        $_app_post='';

        /**
         * For retrive only updated news
         */
        if ($request->has('postfrom'))
        {
            $_app_post = $request->input('postfrom') ;
        }

        /*
		 * For start limit
		 */
        if ($request->has('start'))
        {
            $start = $request->input('start') ;
        }

        /*
         * Number of posts wants to see
         */
        if ($request->has('number'))
        {
            $number_of_posts = $request->input('number') ;
        }

        /*
		 * For getting category type
		 */
        if ($request->has('category'))
        {
            $category = $request->input('category') ;
        }

        /*
         * Number of pages wanted accroding to start and number of post
         */
        $delimit=$number_of_posts; $paged = $start > 0 ? floor($start / $number_of_posts) + 1 : 1;

        /**
         * User number to show access level
         */
        $maxCount = 0;

        $the_query = '';

        $sqlcond='';$col='';$val='';$post__in = array();$keywords_cond_2='';
        $_region=''; $filter = array();

        /*
         * For getting filter type
         */
        if($request->has('filter'))
        {
            $filter = $request->input('filter') ;
        }
		
		/*portfolio filter*/
		if($request->has('portfolio'))
        {
            $common = new Common();
			$temp = $common->getUserPortfolio($user_id, 'news', $appType);			
			$category = $temp['category'];
			$filter['country'] = $temp['country'];
			
			if(empty($temp['category']) && empty($temp['country'])){
				$posts = array();
				return new JsonResponse( $posts);
			}
			
        }///*end portfolio filter*/

        if(isset($filter['mostread'])){ // mostread => have any value or set;
            if ( function_exists('stats_get_csv') && $top_posts = stats_get_csv( 'postviews', array( 'days' => 28, 'limit' => -1 )))
            {
                foreach ( $top_posts as $top_post ) {
                    $post__in[] = $top_post['post_id'];
                }
            }
        }

        /**
         * For region wise filter
         */
        if(isset($filter['country']))
        {
            $catArr = explode(";",$filter['country']);

            $wpostmeta_cod='';
            foreach($catArr as $_val){
                if($wpostmeta_cod)
                    $wpostmeta_cod.=" OR ";
                $wpostmeta_cod.=" ".$wordpress_prifix."_postmeta.meta_value like '%$_val%' ";
            }

            $_region = " AND ( ".$wordpress_prifix."_postmeta.meta_key='country' and ($wpostmeta_cod) )";

        }
        /**
         * For generic search
         */
        elseif( !is_array($filter) )
        {
            $val = trim($filter);///actual value

            $cat = str_replace("-", " ", $val);
            $cat = str_replace(",", " ", $cat);
            ///$catArr = explode(' ', $cat);
            $catArr = explode(' ', $cat);

            foreach($catArr as $subcat):
                $subcat = ucwords(trim($subcat)) ;
                if(trim($subcat)){
                    if($keywords_cond_2)
                        $keywords_cond_2.=' and ';

                    $subcat = str_replace("  ", " ",$subcat);

                    $keywords_cond_2.= " s_res like UPPER('%".$subcat."%') ";
                }
            endforeach;
        }

        $having='';
        if($keywords_cond_2)
        {
            $having =" having ".$keywords_cond_2."";
        }

        $news = new News();
        if($having || $_region)
        {//$_SESSION['mid']==56350

            if(count($post__in) > 0){
                $_post_ids = implode(',',array_unique(array_filter($post__in)));
                $having = " AND ".$wordpress_prifix."_posts.ID in ($_post_ids)";
            }

            $querystr = "
		SELECT ".$wordpress_prifix."_posts.ID,post_title, post_content, REPLACE(UPPER(concat(post_title, post_content)), '  ', ' ') as s_res
		FROM ".$wordpress_prifix."_posts
		LEFT JOIN ".$wordpress_prifix."_postmeta ON (".$wordpress_prifix."_posts.ID = ".$wordpress_prifix."_postmeta.post_id)
		WHERE
		".$wordpress_prifix."_posts.post_status = 'publish'
		AND ".$wordpress_prifix."_posts.post_type = 'post'
		$_region
		$having
		ORDER BY id desc
		";
            $aaa = $news->qryToCommaSepString($querystr);
            $post__in = explode(",", $aaa);
            if(count($post__in) < 1)
                $post__in[] = 0;
        }

        elseif($sqlcond){
            $querystr = "
			SELECT ".$wordpress_prifix."_posts.ID
			FROM ".$wordpress_prifix."_posts
			LEFT JOIN ".$wordpress_prifix."_postmeta ON (".$wordpress_prifix."_posts.ID = ".$wordpress_prifix."_postmeta.post_id)
			WHERE
			$sqlcond
			AND ".$wordpress_prifix."_posts.post_status = 'publish'
			AND ".$wordpress_prifix."_posts.post_type = 'post'
			ORDER BY id desc
			";

            $aaa = $news->qryToCommaSepString($querystr);
            $post__in = explode(",", $aaa);
        }elseif($_app_post!=''){
            list($col, $val_id) = explode(':', $_app_post);
            if($col=='new')
            {///return ids > $val_id
                $querystr = "
				SELECT ".$wordpress_prifix."_posts.ID
				FROM ".$wordpress_prifix."_posts
				WHERE
				".$wordpress_prifix."_posts.post_status = 'publish'
				AND ".$wordpress_prifix."_posts.post_type = 'post'
				AND ".$wordpress_prifix."_posts.ID > $val_id
				ORDER BY id desc
				";
                $aaa = $news->qryToCommaSepString($querystr);
                $post__in = explode(",", $aaa);
                if(count($post__in) < 1)
                    $post__in[] = 0;////no post
            }
            if($col=='edit')
                $post__in[] = $val_id;////for a perticular id
        }

        if($category){
            if(!is_array($category) && strpos($category, ",") !== false)
                $category = explode("," , trim($category));

            if(is_array($category))
            {
                $args=array(
                    'category__in' => $category,
                    'post__in'=> $post__in,
                    'post_status' => 'publish',
                    'post_type' => 'post',
                    'posts_per_page' => $delimit,
                    'paged' => $paged,

                    'caller_get_posts'=> 1,
                    'orderby' => 'post_date',
                    'order' => 'DESC'
                );
            }else{
                $args=array(
                    //'category__in' => $cata_children,
                    'category_name' => $category,
                    'post__in'=> $post__in,
                    'post_status' => 'publish',
                    'post_type' => 'post',
                    'posts_per_page' => $delimit,
                    'paged' => $paged,

                    'caller_get_posts'=> 1,
                    'orderby' => 'post_date',
                    'order' => 'DESC'
                );
            }


        }else{

            $args=array( 'post__in'=> $post__in, 'posts_per_page' => $delimit, 'post_status' => 'publish', 'post_type' => 'post', 'orderby' => 'post_date', 'order' => 'DESC', 'paged' => $paged);
        }

		$args1=array(
				'meta_query'	=> array(
					'relation'		=> 'AND',
					array(
						'key'	 	=> 'news_for_website',
						'value'	  	=> 'steelmint.com',
						'compare' 	=> 'LIKE'
					)
				)		
			);	
		$new_args = array_merge($args, $args1);
		$args = array();
		$args = $new_args;
		
        $posts = $this->query_result($args, $userAccess, $web_domain, $request);
		
		if($request->has('memid'))
        return new JsonResponse($posts ) ;
		else
        return new JsonResponse(array("status#" => "1" , "data#" => $posts ) ) ;
    }

    /**
     * General function to query to wordpress
     * @param $wordpress_args: Wordpress args variable used to query to wordpress
     * @param $userAccess: User access level
     * @param $web_domain: Web domain
     * @return array: Return variables having results.
     */
    private function query_result($wordpress_args, $userAccess , $web_domain , $request){
        $the_query  = new \WP_Query( $wordpress_args );

        $posts = array();
        //$max_num_pages = $the_query->max_num_pages;
        if ( $the_query->have_posts() ) {
            while ( $the_query->have_posts() ) {

                $the_query->the_post();

                //$nws = get_the_title() ;
                $nws = $title = strip_tags(htmlspecialchars_decode(get_the_title(), ENT_QUOTES));
                $title = _shorten_string($nws, 13);
                //$date = get_the_date();
                $date = get_the_time('Y-m-d H:i');
                $myDateTime = new DateTime($date, new DateTimeZone('GMT'));
                $myDateTime->setTimezone(new DateTimeZone('Asia/Kolkata'));
                $date  =  $myDateTime->format('M d, Y H:i');

                $modified = new DateTime($the_query->post->post_modified_gmt, new DateTimeZone('GMT'));
                $modified->setTimezone(new DateTimeZone('Asia/Kolkata'));
                $modified  =  $modified->format('M d, Y H:i');
		
                //$news = strip_tags(htmlspecialchars_decode(get_the_content()));
                $content = get_the_content();
				
				IF(!$request->has('memid')){
					$user_type = '';
					if ($userAccess == -1 )
					{
						$content = apply_filters('the_content', $content);
						$content = str_replace(']]>', ']]&gt;', $content);
						$news = $content .'<link href="https://www.steelmint.com/css/wp_style.css" rel="stylesheet" type="text/css"/>';
						$news = str_replace("<table", '<div style="overflow-x:auto;"><table', $news);
						$news = str_replace("</table>", '</table></div>', $news);
						$breaks = array("\n", "\r");
						$news = str_replace($breaks, " ", $news);
						$user_type = 'paid';
					}
					elseif ($userAccess == 1 )///visitor
					{
						$content = apply_filters('the_content', $content);
						$news = break_text($content, $length=100) . '<SM>...Login';
						
						$breaks = array("\r\n", "\n", "\r");
						$news = str_replace($breaks, " ", $news);
						$user_type = 'login';
					}
					else//upgrade
					{
						$content = apply_filters('the_content', $content);
						$news = break_text($content, $length=200) . '<SM>...Upgrade';
						
						$breaks = array("\r\n", "\n", "\r");
						$news = str_replace($breaks, " ", $news);
						$user_type = 'upgrade';

					}	
				}else{
					$short_content = get_the_content();
					$short_content = apply_filters('the_content', $short_content);
					$short_content = str_replace(']]>', ']]&gt;', $short_content);
					$short_content = stripslashes(strip_tags(html_entity_decode($short_content)));
					$maxlength = 150;
					$short_description = substr($short_content, 0, ($spos = strpos($short_content, '.', $lcount = count($short_content) > $maxlength ? $lcount : $maxlength)) ? $spos : $lcount ).'.';
					
					$breaks = array("\r\n", "\n", "\r");
					$news = str_replace($breaks, " ", $short_description);
				}
                
                $href= str_replace('https://news.steelmint.com', 'news', rtrim(get_permalink(),'/'));
                $href= str_replace('/news/', '/news/', $href);

                if($web_domain!='' && strpos($web_domain, "steelmint.com") === false){
                    $href= str_replace('https://www.steelmint.com/news/', $web_domain, $href);
                }
                //$img = get_post_meta($post->ID, "thumbnail", TRUE);
                $post_thumbnail_id = get_post_thumbnail_id(get_the_ID());
                //$thumb_image_url = wp_get_attachment_url( $post_thumbnail_id );
                //$medium_image_url = wp_get_attachment_url($post_thumbnail_id, 'medium');
                $medium_image_url = wp_get_attachment_image_src($post_thumbnail_id, $size='large', $icon = false);
                $thumb_image_url = wp_get_attachment_image_src($post_thumbnail_id, $size='thumbnail', $icon = false);

                $subcat = get_the_category();
				
				
				
                $row['ID'] = strval(get_the_ID());
                $row['post_title'] = $title;
                $row['post_content'] = $news;
               // $row['description'] = $short_description;
                $row['sub_category'] = $subcat[0]->cat_name ;
                if($subcat[0]->parent)
					$row['category'] = get_cat_name( $subcat[0]->parent ) ;
				else
					$row['category'] = $subcat[0]->cat_name;
                $row['author_name'] = get_the_author();
                $row['href'] = $href;
                $row['image'] = $medium_image_url[0]; //$thumb_image_url[0];
                $row['medium_image'] = $medium_image_url[0];

                $row['post_date'] = ($date);
                $row['posted_on'] = _timeSince($date);
                $row['post_modified'] = $modified ;
                $row['user_type'] = $user_type ;
                if ( empty( $row['sub_category']) )
                    $row['sub_category'] = 'UNCATEGORIZED';
                if ( !empty( $row['category']) )
                    $posts[] = $row;
            }
            //print_r($row);
            wp_reset_query();
        }

        return $posts ;
    }
}