<?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 Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Auth\authentication;

use App\Http\Controllers\Controller;

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

use App\Http\Controllers\Action\Common ;
/**
 * Class newNEWSController: for news
 * @package App\Http\Controllers
 */
class newNEWSController extends Controller
{
	
/*  ================= START =============:  new funcitons fetching data from new table tbl_news_post */	
	public function get_news_by_id(Request $request, $id)
    {
    	include('/home/steelmin/public_html/hf.php');

        $userAccess = 0;
        $web_domain = 'steelmint.com';

        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');
            }
        } else {
		    $userAccess = 1;
		}

		$result = array();
		$result[] = get_news_by_id_inner($id);

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

        if($request->has('memid')) {
        	return new JsonResponse($posts) ;
		} else {
        	return new JsonResponse(array("status#" => "1" , "data#" => $posts));			
        }
    }

	public function get_all_news(Request $request)
    {
		
    	include('/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( $request->has('token')) {
			 $token = $request->input('token');
		}

        $userAccess = 0;
        $web_domain = 'steelmint.com';

        if($request->has('token') || $request->has('memid')) { //user is logged in
            if($request->has('memid')) {
				$memid = $request->input('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);
                $userAccess = $us->getTakenServicesByUser();
            } else {
			 	return new JsonResponse(array(
                    "status#" => "403",
                    "message#" => "Unauthorized action. Token access denied"
                )) ;
			}
        } else {
		    $userAccess = 1;
		}
		
        $start = 0 ;
        $number_of_posts = 25 ;
        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 category type
		 */
        if($request->has('category')) {
        	$newsFilter['categories'] = $request->input('category');

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

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

            return new JsonResponse(array("status#" => "1" , "data#" => $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);

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

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

		    } else {
		    	$filter = $request->input('filter');
		    }
        }
		
		/*portfolio filter*/
		if($request->has('portfolio')) {
           $common = new Common();
			$temp = $common->getUserPortfolio($user_id, 'news');
			
			if(empty($temp['category']) && empty($temp['country'])){
				$posts = array();
				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, '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);

            

           /* if($category_ids) {
                foreach($category_ids as $category_id) {
                    if(in_array($category_id, $raw_material_alt)) {
                        $category_id = 8;
                    }
                    if(isset($categories['data#']) && !empty($categories['data#'])) {
                        foreach($categories['data#'] as $cat) {
                            if($cat['cat_id'] == $category_id) {
                                $category[] = $cat['cat_name'];
                                break;
                            }
                        }
                    }
                }
            }*/
            
			$newsFilter['categories'] = implode(",", array_values(array_unique($category)));

            $country = rtrim($temp['country'], ";");
            $countries = explode(";", $country);
            $country_alts = array(
                'asia'  =>  array(
                    'Japan, Korea',
                    'Australia',
                    'south east asia'
                ),
                'bangladesh'  =>  array(
                    'Pakistan, Bangladesh, Nepal'
                ),
                'mena'  =>  array(
                    'middle east africa'
                ),
                'europe, us and asia pacific' => array(
                    'cis nations',
                    'europe',
                    'us/canada',
                    'brazil'
                )
            );
            
            $regions = array();

            if($countries) {
                foreach($countries as $cont) {
                    $matched = false;
                    foreach($country_alts as $key => $ca) {
                        foreach($ca as $c) {
                            if(strtolower($cont) == $c) {
                                $regions[] = $key;
                                $matched = true;
                                break;
                            }
                        }
                        if($matched) {
                            break;
                        }
                    }
                    if(!$matched) {
                        $regions[] = $cont;
                    }
                }
            }

			$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']);
        }

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

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

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

    }

    public function getFormatedNewsData($posts = array(), $userAccess = 1, $web_domain = '', $request)
    {
    	$results = 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']));
                $posted_on = $this->_timeSince($post['post_date']);
                $post_modified = date('M d, Y H:i', strtotime($post['updated_at']));

                $content = $post['post_content'];
                $user_type = '';

                if(!$request->has('memid')) {
                	if($userAccess == -1) {
                		$breaks = array("\n", "\r");
						$content = str_replace($breaks, " ", $content);
						$user_type = 'paid';
                	} 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_modified,
                	'user_type'		=>	$user_type,
                );
    		}
    	}

    	return $results;
    }

    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 */	
}