<?php
namespace App\Http\Controllers\v2019;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Auth\authentication;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Auth\User;
use App\Http\Controllers\Action\Common;

class PricesController extends Controller
{ 
    public $appType = 'SM' ;
	public function __construct(Request $request) {
        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;			
        }
		if($request->has('appType') && $request->input('appType') == true) {
            $this->appType = $request->input('appType');		
        }elseif($request->has('filters')){
			 $filter = $request->input('filters');
			 if(!empty($filter['app_type'])){
					$this->appType = 'CM';
			 }
		} else if($request->has('app_type') && $request->input('app_type') == true) {
            $this->appType = $request->input('app_type');		
        }
    }
	public function indianPriceCategories(Request $request){
		if( 'CM' == $this->appType )
			$filename = "https://www.steelmint.com/indianpriceCats_coal.json"; 
		else
			$filename = "https://www.steelmint.com/indianpriceCats.json"; 
		return file_get_contents($filename);		
	}   
	
	public function getPricesSearch(Request $request)
    {


		if($request->has('filters')){
			//$filters = $request->input('filters');
			$sterm = '';
		}elseif($request->has('sterm'))
			$sterm = strtolower($request->input('sterm'));
		else
			return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Search term missing!")));

		if($request->has('sectionType'))
			$sectionType = strtolower($request->input('sectionType'));
		else
			$sectionType = '';
		
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters');
		
		$result = \ApiQuery::getPricesSearchRows($sterm, $sectionType, $filters);	
		$code = 1001;				
		$message = "Success";

		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));		
	}	
	public function getPrices(Request $request)
    {
		//throw data for reliance
		if($request->has('api_key')){
			$api_key = $request->input('api_key');

			if($request->has('fromdate'))
				$fromdate = $request->input('fromdate');
			if($request->has('todate'))
				$todate = $request->input('todate');
			
			//check if api_key is valid	
			//DB::enableQueryLog(); 
			$api_key_dtls = 
				DB::table('tbl_customized_apis')
				->	select(array('considerTableName', 'enddate', 'prices_assessments_to_show', 'showDataFrom'))
				->	where("api_key","=",$api_key)
				->	where("enddate",">=",date("Y-m-d"))
				->	get();		
			//dd(DB::getQueryLog());
			//print_r($api_key_dtls);
			if( count($api_key_dtls) == 0 )	{
				$code = 2001;				
				$message = "api key is invalid or it has expired.";

				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
				
			} else {
				$currency = "Currency";
				$memid = 116686;
				$filters = array();
				if($request->has('filters') && !empty($request->input('filters')))
					$filters = $request->input('filters');
				$prices_assessments_to_show = $api_key_dtls[0]['prices_assessments_to_show'];
				$trade_type = $api_key_dtls[0]['trade_type'];
				
				if( '' != $prices_assessments_to_show ){
    				if($trade_type){
    					$trade_typeArr = explode(',', $trade_type);
    					foreach($trade_typeArr as $tt){
    						$filters["itemID"][$tt] = explode(',', $prices_assessments_to_show);
    					}
    					if($trade_type=='f')
    						$filters["tradeType"] = 'domestic';
    				}else{
    					$filters["itemID"]["f"] = explode(',', $prices_assessments_to_show);
    					$filters["tradeType"] = 'domestic';
    				}
				} else {
				    if ( "qkoeI6XB7YZhxupVE2Oe" == $api_key ){
				        $filters["itemID"]["f"] = explode(',', "1067,1234,1004");
    					$filters["itemID"]["cnf"] = explode(',', "6,65");
				    }
				}
				
				$source = "details";
				$resourceType = "web";
				$offset=0;
				$pageValue=1;
				
				if ($request->has('pageValue') && $request->input('pageValue')!='')
					$pageValue = $request->input('pageValue');	
				$offset = ($pageValue-1)* 20;		
				
				$cntOfRecs = 1;
				$filters['considerTableName'] = $api_key_dtls[0]['considerTableName'];
				if( isset($filters['fromdate']) && $filters['fromdate'] != '' ) {
					if($filters['fromdate'] < $api_key_dtls[0]['showDataFrom']){
						$code = 2001;				
						$message = "You are trying to access data beyond authorized date.";

						return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
						
					} else {
					    if( '' != $prices_assessments_to_show ){
						    $filters['prices_assessments_to_show'] = $prices_assessments_to_show;
					    }  
						$cntOfRecs = \ApiQuery::getPricesRowsCnt($filters);
					}
				}
				
				$result = \ApiQuery::getPricesRows($memid, $source, $resourceType, $type='', $filters, $accessType,20, $offset, "SM", $currency);	
				return new JsonResponse(array("status"=>array("code" => 1001, "message" => "Success"), "data"=> $result, "pagesCount"=> ceil($cntOfRecs / 20)));				
			}	
		}		
		$resourceType = "app";
		$source = "listing";
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('source'))
			$source = strtolower($request->input('source'));
		
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
			
			///cphrase code
			if((isset($filters['searchTerms']) && $filters['searchTerms']!='')){
				$common = new Common();
				$innerFilterCond = $common->getSearchTermFilterCond($filters['searchTerms']);
			    ///$innerFilterCond = $this->getSearchTermFilterCond($filters['searchTerms']);
				
				if(!empty($innerFilterCond) && isset($innerFilterCond['price']) && !empty($innerFilterCond['price'])){
				 $filters['innerFilterCond'] = $innerFilterCond['price'];
					if(!in_array('tbl_exim_master', array_keys($innerFilterCond['price']))){
						$filters['tradeType'] = 'regional';
						}/* elseif(!in_array('tbl_dom_master', array_keys($innerFilterCond['price']))){
						$fields['filters']['tradeType'] = 'import';
					 } */
					unset($filters['searchTerms']);
			  }
		   }////
			if( isset($filters['app_type']) && $filters['app_type'] != ''){
				$this->appType = $filters['app_type'];
			}
		}
		
		$currency = '';
		if( $request->has('currencyName')) {
            $currency = $request->input('currencyName') ;
        }
		
		$offset=0;
		$pageValue=1;
		
		if ($request->has('pageValue') && $request->input('pageValue')!='')
			$pageValue = $request->input('pageValue');	
		
		$offset = ($pageValue-1)* DEFAULT_PRICES_LIMIT;		
		$user_id=0;
		if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token);
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}elseif ($resourceType=='web' && $request->has('memid') && $request->input('memid')!=''){
								
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}
		
		$accessType='pre';//for visitor///
		
		if($user_id){
			$user = new User($user_id, $this->appType);
			///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Prices');
			
			if ($isAccessible==-1) {
				$accessType = 'post';
			}else{
				$accessType = 'pre';
			}
		}		
		
		if($pageValue>1 || count($filters)>0){
			
			$result = \ApiQuery::getPricesRows($user_id, $source, $resourceType, $type='', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);			
			
		}else {/// data from json array file 		
			$result = \ApiQuery::getPricesRows($user_id, $source, $resourceType, $type='default', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);
		}
		/* 		$filename='';
		//if($pageValue>1 || count($filters)>0){
		if($pageValue>1){
			
			$result = \ApiQuery::getPricesRows($user_id, $source, $resourceType, $type='', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);			
			
		}else {/// data from json array file 	
			switch(strtolower($source)){
				case 'keyindex':
					$filename = "price_explore_$accessType.json";
				break;
				case 'commodity':
				case 'commoditywise':
					$ftr_commodityID =0;
					if(isset($filters['commodityID']) && !empty($filters['commodityID'])) {
						$ftr_commodityID = implode("_", $filters['commodityID']);
					}
				    $filename = "price_commodity_wise_".$ftr_commodityID."_$accessType.json";
				break;
				case 'region':
				case 'regionwise':
					$ftr_commodityID =0;
					if(isset($filters['commodityID']) && !empty($filters['commodityID'])) {
						$ftr_commodityID = implode("_", $filters['commodityID']);
					}
					$filename = "price_region_wise_".$ftr_commodityID."_$accessType.json";
				break;
				case 'mapview':
					if($pageValue>1 || count($filters)>0){
						$filename='';
					}else{
						if(strtolower($currency)=='inr'){
							$filename = "price_map_usd_$accessType.json";
						}elseif(strtolower($currency)=='usd'){
							$filename = "price_map_inr_$accessType.json";
						}else{
							$filename = "price_map_default_currency_$accessType.json";						
						}
					}
				break;
				case '':
				case 'listing':
					if($pageValue>1 || count($filters)>0){
						$filename='';
					}else{
						if(strtolower($currency)=='inr'){
							$filename = "price_landing_usd_$accessType.json";
						}elseif(strtolower($currency)=='usd'){
							$filename = "price_landing_inr_$accessType.json";
						}else{
							$filename = "price_landing_default_currency_$accessType.json";
						}
					}
				break;
			}
		   // echo storage_path('v2019/Json/App').'/'.$filename;
            if ($filename!='' && file_exists(storage_path('v2019/Json/App').'/'.$filename)){
                $filename=storage_path('v2019/Json/App').'/'.$filename;
                // return glob($filename, GLOB_BRACE);
                return file_get_contents($filename);
            }else{
                $result = \ApiQuery::getPricesRows($user_id, $source, $resourceType, $type='', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);
            }
			
		} */
		
		$code = 1001;				
		$message = "Success";

	   //if($resourceType == "web" && $source == 'mapview') 
	   //	  $result = $this->result_web($result);

			
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result, "defaultItemsCount"=> 5));
    }

	private function result_web(&$result){
		$result_with_viewmore = array();$vmore=array("parent"=>"","val"=>"","indexer"=>false);
		usort($result, array($this, "build_sorted"));
		foreach($result as $k=>$v){
			   $vmore["indexer"] = $vmore["val"] == $v["regionID"] ? true : false;
			   if($vmore["indexer"]){
				   $vmore["parent"] = $vmore["parent"] == "" ? count($result_with_viewmore)-1:$vmore["parent"];
				   $result_with_viewmore[$vmore["parent"]]["viewmore"][] = $v;
			   }else{
				   $vmore["parent"] = "";
				   $result_with_viewmore[] = $v;
			   }  
			      
			   $vmore["val"] = $v["regionID"];
		}
		return $result_with_viewmore;
	}
	
	private function build_sorted ($a, $b){
			if ($a["regionID"] == $b["regionID"]) {
				return 0;
			}
			return ($a["regionID"] < $b["regionID"]) ? -1 : 1;
	}
	
    public function getPriceDetails(Request $request){
		$resourceType = "app";
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
				$this->appType = 'CM';
			}
		}	

		//$result = array();	
		$result = null;	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$itemID=0;
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');
			$filters['itemID'] = $itemID;
			if($request->has('priceType') && !empty($request->input('priceType'))){
				$filters['priceType'] = $request->input('priceType');;
			}
		}
		
		if($resourceType=='app' && $request->has('accessToken') && !empty($request->input('accessToken'))){
		    $auth = new authentication();	
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token);	
		}elseif($resourceType=='web' && $request->has('memid') && !empty($request->input('memid'))){
			$memid = $request->input('memid');
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}
		
		if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
			$i_id = 5355;//75;
			$priceType = "fob";
		} else {
			$i_id = 1067;	
			$priceType = "f";		
		}
		if ($request->has('requiredFor') && $request->input('requiredFor')=='home_pre_login'){
			///billet-> Ex-Raipur 
			//$requiredfor = 'details';
			$itemID = $i_id;
			$filters['itemID'] = $itemID;
			$filters['priceType'] = $priceType;
		}
		
		if(!$itemID){
			$code = 2013;
			$message = "Invalid! itemID missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		$currency = '';
		if( $request->has('currencyName')) {
            $currency = $request->input('currencyName') ;
        }elseif( $request->has('currency')) {
            $currency = $request->input('currency') ;
        }
		
		$accessType = 'pre';
		if($memid){
			///full data///
			//include_once "/home/steelmin/public_html/api/storage/v2019/web/web_prices_details_pre.php"; 
			$user = new User($memid, $this->appType);
			///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Prices');
			if ($isAccessible==-1) {
				$accessType = 'post';
			}
		}
		if ($request->has('requiredFor') && $request->input('requiredFor')=='home_pre_login'){
			$accessType = 'post';
			/* echo "<pre>";
			print_r($filters); */
		}
		
		$resultDetails = \ApiQuery::getPricesRows($memid, $source='details', $resourceType, $type='', $filters, $accessType,50, $offset=0, $this->appType, $currency);
		if(count($resultDetails)>0 && $resourceType!='app'){
			$result = $resultDetails[0];
		}else{
			$result = $resultDetails;
		}
		$code = 1001;
		$message = "Success";
		
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}

	public function getPricesGraph(Request $request)
    {      
		$result = array();
	    $resourceType = "app";
			
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		
		$user_id=0;
		///$user_id = '' ;
		$relation_id = 0 ;
		$price_type_prefix = 'f';
		$assesment = 'W';
		$currency = '';		
		$dateFilter = array();
		$requiredfor='';
		$_logStartDate='';
		
		if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token);
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}elseif ($resourceType=='web' && $request->has('memid') && $request->input('memid')!=''){
								
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}elseif ($request->has('requiredFor') && $request->input('requiredFor')=='home_pre_login'){

			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
				$i_id = 75;
				$priceType = "fob";
				$assesment = 'W';			
			} else {
				$i_id = 1067;	
				$priceType = "f";
				$assesment = 'D';			
			}
			
			///billet-> Ex-Raipur 
			//$requiredfor = 'home_pre_login';
			$relation_id = $i_id;
			$price_type_prefix = $priceType;
			
			$dateFilter['fromDate']  = date('Y-m-d', strtotime('-6 months'));//'2015-01-01';
			$dateFilter['toDate']  = date('Y-m-d');//'2015-12-31';
		}
				
		include_once($_ENV['COMMON_ROOT_PATH'].'/mappNew.php') ;

				
		if ($request->has('itemID')) {
            $relation_id = $request->input('itemID') ;
        }
		
		if(!$relation_id){
			return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Invalid ItemID.")));
		}
		
		if ($request->has('priceType')) {
            $price_type_prefix = $request->input('priceType') ;
        }

        if( $request->has('assesment')) {
            $assesment = $request->input('assesment') ;
        }
		
		if( $request->has('currencyName')) {
            $currency = $request->input('currencyName') ;
        }
		

		if( $request->has('requiredFor')) {
            $requiredfor = $request->input('requiredFor') ;
        }
		
		$itemNo='';
		if( $request->has('itemNo')) {
            $itemNo = $request->input('itemNo');
        } 
		
		if($request->has('fromDate') && !empty($request->input('fromDate'))){
		    $fromDate = $request->input('fromDate');
			$dateFilter['fromDate'] = $fromDate;			
		}
		
		if($request->has('toDate') && !empty($request->input('toDate'))){
		    $toDate = $request->input('toDate');
			$dateFilter['toDate'] = $toDate;			
		}
		
		$assessmentType ='';
		if($request->has('assessmentType') && !empty($request->input('assessmentType'))){
		    $assessmentType = $request->input('assessmentType');	
			$dateFilter['assessmentType'] = $assessmentType;			
		}
		
		$convertType ='';
		if($request->has('convertType') && !empty($request->input('convertType'))){
		    $convertType = $request->input('convertType');	
			$dateFilter['convertType'] = $convertType;			
		} 
		
		$code = 1001;
		$message = "Success";
		$f_heading = '';
		if($requiredfor!='comparison'){
			$result = array();
			//echo "1:" . $user_id;
			if($user_id){
				$user = new User($user_id, $this->appType);
				//$isAccessible =  $user->isAccessible($resourceType, $section='Price Graph');
				$isAccessible =  $user->isAccessible($resourceType, $section='Price Graph');
				//if($isAccessible==-1 )
				if(1 ){//send empty data for app when have no access
				////if(116695==$user_id){echo $this->appType; print_r(session()->all());}
					$result = getGraphDataForIdNew($resourceType, $user_id , $relation_id , $price_type_prefix , $assesment, $appType=$this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter,$f_heading);
					
				}
			}elseif (1){//$requiredfor=='home_pre_login' //send empty data for app when have no access
				$result = getGraphDataForIdNew($resourceType, $user_id , $relation_id , $price_type_prefix , $assesment, $appType=$this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter,$f_heading);
			}
		}else{
			$result = getGraphDataForIdNew($resourceType, $user_id , $relation_id , $price_type_prefix , $assesment, $appType=$this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter,$f_heading);
		}
				
		$res = array("status"=>array("code" => $code, "message" => $message), "data"=> $result);
		
		$res["currency"] = $currency;
		
		if($requiredfor=='comparison'){
			$res["startDate"] = $_logStartDate;
		}
	    return new JsonResponse($res);
    } 
	
	public function getCostIndex(Request $request)
    {      
	   $result = array();
	   include_once "/home/steelmin/public_html/api/storage/v2019/costindex_pre.php";
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
           // $auth = new authentication();
           $token = $request->input('accessToken');
           if(empty($token)){
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found.";
			}else{
				///full data///
				$code = 1001;
				$message = "Success";
			}
        }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		}
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    } 
	
	public function getPortfolioListItems(Request $request)
    {      
	    $result = array();
	    include_once "/home/steelmin/public_html/api/storage/v2019/portfolio_post.php";
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
           // $auth = new authentication();
           $token = $request->input('accessToken');
           if(empty($token)){
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found.";
			}else{
				///full data///
				$code = 1001;
				$message = "Success";
			}
        }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		}
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    } 
	///Comparison/ Display Saved comparison
	public function compare(Request $request)
    {      
	    /* $result = array();
	   
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
           // $auth = new authentication();
           $token = $request->input('accessToken');
           if(empty($token)){
				///not loggedin/visitor///
				$code = 2013;
				$message = "User not found."; 
			}else{
				 //include_once "/home/steelmin/public_html/api/storage/v2019/saved_comparison_display_listing.php";
				 include_once "/home/steelmin/public_html/api/storage/v2019/save_compare.php";
				///full data///
				$code = 1001;
				$message = "Success";
			}
        }else{
			///not loggedin/visitor///
			
			$code = 1001;
			$message = "Success";
		} */
		
		$user_id=0;
		if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token);
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}elseif ($resourceType=='web' && $request->has('memid') && $request->input('memid')!=''){
								
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}
		
		$resourceType = "app";
		$filters = array();
		//return $request->all();
		/* if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters'); */
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($resourceType=='web' || $resourceType=='app'){
			if($request->has('item1') && !empty($request->input('item1'))){
				$item1 = $request->input('item1');			
			}else{
				$code = 2013;
				$message = "Invalid! item1 missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}		
		
			if($request->has('item2') && !empty($request->input('item2'))){
				$item2 = $request->input('item2');			
			}else{
				$code = 2013;
				$message = "Invalid! item2 missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
		}else{
			if($request->has('item1ID') && !empty($request->input('item1ID'))){
				$relationID1 = $request->input('item1ID');			
			}else{
				$code = 2013;
				$message = "Invalid! item1ID missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if($request->has('item2ID') && !empty($request->input('item2ID'))){
				$relationID2 = $request->input('item2ID');			
			}else{
				$code = 2013;
				$message = "Invalid! item2ID missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if($request->has('item1TradeType') && !empty($request->input('item1TradeType'))){
				$tradeType1 = $request->input('item1TradeType');			
			}else{
				$code = 2013;
				$message = "Invalid! item1 tradeType missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if($request->has('item2TradeType') && !empty($request->input('item2TradeType'))){
				$tradeType2 = $request->input('item2TradeType');			
			}else{
				$code = 2013;
				$message = "Invalid! item2 tradeType missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			$item1['dataType'] = 'price';
			$item2['dataType'] = 'price';
			
			$item1['relationID'] = $relationID1;
			$item2['relationID'] = $relationID2;
			
			if(strtolower($tradeType1)=='domestic')
				$tradeType1 = 'f';
			elseif(strtolower($tradeType1)=='import')
				$tradeType1 = 'cnf';
			elseif(strtolower($tradeType1)=='export')
				$tradeType1 = 'fob';
			
			if(strtolower($tradeType2)=='domestic')
				$tradeType2 = 'f';
			elseif(strtolower($tradeType2)=='import')
				$tradeType2 = 'cnf';
			elseif(strtolower($tradeType2)=='export')
				$tradeType2 = 'fob';
				
			$item1['tradeType'] = $tradeType1;
			$item2['tradeType'] = $tradeType2;
		}
		
		if($request->has('compareName') && !empty($request->input('compareName'))){
		    $compareName = $request->input('compareName');			
		}/* else{
			$code = 2013;
			$message = "please enter compare title.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		} */
		
		if(($resourceType=='web' || $resourceType=='app') && !is_array($item1) && !is_array($item2)){
			$code = 2013;
			$message = "Invalid Input.";	
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));			
		}
		
		if($request->has('fromDate') && !empty($request->input('fromDate'))){
		    $fromDate = $request->input('fromDate');			
		}else{
			$code = 2013;
			$message = "please enter fromDate.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		if($request->has('toDate') && !empty($request->input('toDate'))){
		    $toDate = $request->input('toDate');			
		}else{
			$code = 2013;
			$message = "please enter to Date.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		$comparisonId=0;
		if($request->has('comparisonID') && !empty($request->input('comparisonID'))){
		    $comparisonId = $request->input('comparisonID');			
		}
		
		$assessmentType ='';
		if($request->has('assessmentType') && !empty($request->input('assessmentType'))){
		    $assessmentType = $request->input('assessmentType');			
		}
		
		include($_ENV['COMMON_ROOT_PATH'].'/mappNew.php') ;

		$user_id = 0 ;
		if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token);
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}elseif ($resourceType=='web' && $request->has('memid') && $request->input('memid')!=''){
								
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}
		
		$relation_id = $id ;
		$price_type_prefix = 'f';
		$assessment = 'W';
		$currency = '';
		
		$dataType1 = isset($item1['dataType'])?$item1['dataType']:'';
		$dataType2 = isset($item2['dataType'])?$item2['dataType']:'';
		
		$relation_id1 = isset($item1['relationID'])?$item1['relationID']:'';
		$relation_id2 = isset($item2['relationID'])?$item2['relationID']:'';
		
		$price_type_prefix1 = isset($item1['tradeType'])?$item1['tradeType']:'';
		$price_type_prefix2 = isset($item2['tradeType'])?$item2['tradeType']:'';
		
		if ($request->has('priceType')) {
            $price_type_prefix = $request->input('priceType') ;
        }

        if( $request->has('assessment')) {
            $assessment = $request->input('assessment') ;
        }
		$currencyName='';
		if( $request->has('currencyName')) {
            $currency = $request->input('currencyName') ;
			$currencyName=$currency;
        }		
		$requiredfor='comparison';$_logStartDate='';
		if( $request->has('requiredfor')) {
            $requiredfor = $request->input('requiredfor') ;
        }
		
		if( $request->has('requiredFor')) {
            $requiredfor = $request->input('requiredFor') ;
        }
		
		$dateFilter = array('fromDate'=>$fromDate, 'toDate'=>$toDate, 'assessmentType'=>$assessmentType);
		$code = 1001;
		$message = "Success";
		
		$result['item1'] = getGraphDataForIdNew($resourceType, $user_id , $relation_id1 , $price_type_prefix1 , $assessment, $appType=$this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter, $f_heading);
		
		$result["currency1"] = $currency;
		$result["item1Title"] = $f_heading;
		
		$currency=$currencyName;
		
		$result['item2'] = getGraphDataForIdNew($resourceType, $user_id , $relation_id2 , $price_type_prefix2 , $assessment, $appType=$this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter, $f_heading);
		
		$result["currency2"] = $currency;
		$result["item2Title"] = $f_heading;
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	   
    } 
	
	///
	public function compareSave(Request $request)
    {     
	    $resourceType = "app";
		$filters = array();
		//return $request->all();
		/* if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters'); */
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($resourceType=='web' || $resourceType=='app'){	
			if($request->has('item1') && !empty($request->input('item1'))){
				$item1 = $request->input('item1');			
			}else{
				$code = 2013;
				$message = "Invalid! item1 missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if($request->has('item2') && !empty($request->input('item2'))){
				$item2 = $request->input('item2');			
			}else{
				$code = 2013;
				$message = "Invalid! item2 missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
		}else{//for app
			
			if($request->has('item1ID') && !empty($request->input('item1ID'))){
				$relationID1 = $request->input('item1ID');			
			}else{
				$code = 2013;
				$message = "Invalid! item1ID missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if($request->has('item2ID') && !empty($request->input('item2ID'))){
				$relationID2 = $request->input('item2ID');			
			}else{
				$code = 2013;
				$message = "Invalid! item2ID missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if($request->has('item1TradeType') && !empty($request->input('item1TradeType'))){
				$tradeType1 = $request->input('item1TradeType');			
			}else{
				$code = 2013;
				$message = "Invalid! item1 tradeType missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if($request->has('item2TradeType') && !empty($request->input('item2TradeType'))){
				$tradeType2 = $request->input('item2TradeType');			
			}else{
				$code = 2013;
				$message = "Invalid! item2 tradeType missing.";			
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
			
			if(strtolower($tradeType1)=='domestic')
				$tradeType1 = 'f';
			elseif(strtolower($tradeType1)=='import')
				$tradeType1 = 'cnf';
			elseif(strtolower($tradeType1)=='export')
				$tradeType1 = 'fob';
			
			if(strtolower($tradeType2)=='domestic')
				$tradeType2 = 'f';
			elseif(strtolower($tradeType2)=='import')
				$tradeType2 = 'cnf';
			elseif(strtolower($tradeType2)=='export')
				$tradeType2 = 'fob';
				
			$item1['dataType'] = 'price';
			$item2['dataType'] = 'price';
			
			$item1['relationID'] = $relationID1;
			$item2['relationID'] = $relationID2;
			
			$item1['tradeType'] = $tradeType1;
			$item2['tradeType'] = $tradeType2;
		}
		
		if($request->has('compareName') && !empty($request->input('compareName'))){
		    $compareName = $request->input('compareName');			
		}else{
			$code = 2013;
			$message = "please enter compare title.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		if(($resourceType=='web'  || $resourceType=='app') && !is_array($item1) && !is_array($item2)){
			$code = 2013;
			$message = "Invalid Input.";	
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));			
		}
		
		$tenure='';
		if($request->has('tenure') && !empty($request->input('fromDate'))){
		    $tenure = $request->input('tenure');			
		}
		
		if($request->has('fromDate') && !empty($request->input('fromDate'))){
		    $fromDate = $request->input('fromDate');			
		}elseif($tenure==''){
			$code = 2013;
			$message = "please enter fromDate.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		if($request->has('toDate') && !empty($request->input('toDate'))){
		    $toDate = $request->input('toDate');			
		}elseif($tenure==''){
			$code = 2013;
			$message = "please enter to Date.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		$comparisonId=0;
		if($request->has('comparisonID') && !empty($request->input('comparisonID'))){
		    $comparisonId = $request->input('comparisonID');			
		}
		$assessmentType ='';
		if($request->has('assessmentType') && !empty($request->input('assessmentType'))){
		    $assessmentType = $request->input('assessmentType');			
		}
		$screenImage='';
		if($request->has('screenImage') && !empty($request->input('screenImage'))){
		    $screenImage = $request->input('screenImage');			
		}
		
		if($request->has('source') && !empty($request->input('source'))){
		    $source = $request->input('source');			
		}
		
		if($resourceType=='app' && $request->has('accessToken') && !empty($request->input('accessToken'))){
		    $auth = new authentication();	
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token);	
		}elseif($resourceType=='web' && $request->has('memid') && !empty($request->input('memid'))){
			$memid = $request->input('memid');
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}	
		
		if($memid){
			$screenImage ="";
			$screenImage = date('YmdHi').'_'.$memid . ".png";
			if($request->has('screenImage')) {
				$str= str_replace('\\','',$request->input('screenImage'));
				$str= str_replace(' ','+',$str);
				$str = base64_decode($str);
				
				$screenImage = date('YmdHi').'_'.$memid . ".png";
				file_put_contents("/home/steelmin/public_html/api/public/uploads/compare/" . $screenImage , $str);
			}
			
			$uData = array(
					"updatedOn"=>$GLOBALS['currDateTime'],
					"memid"=>$memid,
					"compareName"=>$compareName,
					"screenImage"=>$screenImage,
					"dataType1"=>$item1['dataType'],
					"dataType2"=>$item2['dataType'],
					"tradeType1"=>isset($item1['tradeType'])?$item1['tradeType']:'',
					"tradeType2"=>isset($item2['tradeType'])?$item2['tradeType']:'',
					"commodityID1"=>isset($item1['commodityID'])?$item1['commodityID']:'',
					"commodityID2"=>isset($item2['commodityID'])?$item2['commodityID']:'',
					"regionID1"=>isset($item1['regionID'])?$item1['regionID']:'',
					"regionID2"=>isset($item2['regionID'])?$item2['regionID']:'',
					"relationID1"=>isset($item1['relationID'])?$item1['relationID']:'',
					"relationID2"=>isset($item2['relationID'])?$item2['relationID']:'',					
					
					"columnNameOfRegion1"=>isset($item1['columnNameOfRegion'])?$item1['columnNameOfRegion']:'',			
					"columnNameOfCommodity1"=>isset($item1['columnNameOfCommodity'])?$item1['columnNameOfCommodity']:'',
					"2ndLevel1"=>isset($item1['childHeaderName'])?$item1['childHeaderName']:'',
					"2ndLevel1Value"=>isset($item1['childHeaderValue'])?$item1['childHeaderValue']:'',
					"2ndLevel1headerColumn"=>isset($item1['childHeaderColumn'])?$item1['childHeaderColumn']:'',	
					
					"columnNameOfRegion2"=>isset($item2['columnNameOfRegion'])?$item2['columnNameOfRegion']:'',			
					"columnNameOfCommodity2"=>isset($item2['columnNameOfCommodity'])?$item2['columnNameOfCommodity']:'',
					"2ndLevel2"=>isset($item2['childHeaderName'])?$item2['childHeaderName']:'',
					"2ndLevel2Value"=>isset($item2['childHeaderValue'])?$item2['childHeaderValue']:'',
					"2ndLevel2headerColumn"=>isset($item2['childHeaderColumn'])?$item2['childHeaderColumn']:'',
					
					"tenure"=>$tenure,
					"fromDate"=>$fromDate,
					"toDate"=>$toDate,
					"assessmentType"=>$assessmentType,
					"resourceType"=>$resourceType
				);
			
				//else insert new device details
			if($comparisonId<=0){//insert
				$uData["createdOn"]= $GLOBALS['currDateTime'];
				$comparisonId = DB::table('tbl_compare')->insertGetId($uData);				
			}else{
				
				DB::table('tbl_compare')
							->where("id" , "=" , $comparisonId )
							->update($uData) ;
			}
			
			$code = 1001;
			$message = "Successfully Saved";
			$result['comparisonId'] = $comparisonId;
		}else{
			$code = 2100;
			$message = "Invalid User or User not found."; 
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }  
	
	//Compare - Mapping data
	public function compareFilterList(Request $request)
    {      
	    $result = array();
		/* $section = $request->input('section');
		$tradeType = $request->input('tradeType');
		$regionID = $request->input('regionID'); */
		
		$resourceType = "app";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token);
		}elseif ($resourceType=='web' && $request->has('memid') && $request->input('memid')!=''){
								
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
		}

		$filters = array();
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
			if( isset($filters['app_type']) && $filters['app_type'] != '')
				$this->appType = $filters['app_type'];
		}

		
		$deviceType = "";
		if ($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));
		
		if($user_id) {
			/* $user = new User($user_id, $this->appType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Price Graph');
			
			if(!empty(Session::get('sectionFromDate'))){			
				$sectionFromDate = Session::get('sectionFromDate');
				$sectionTodate = Session::get('sectionTodate');			
			}
			 */
			$result = \ApiQuery::getPricesFilterNew($user_id, $this->appType, $deviceType);
			$code = 1001;
			$message = "Success";
		}else{
			$code = 2100;
			$message = "Invalid User or User not found."; 
		}
		
		/* if($regionID==''){
			$code = 9999;
			$message = "Please select region."; 
		}elseif($tradeType==''){
			$code = 9999;
			$message = "Please select tradeType."; 
		}else 
		{
			$result = \ApiQuery::getPricesFilter($section, $tradeType, $regionID, $this->appType);
			$result = \ApiQuery::getPricesFilterNew($section, $this->appType);
			$result = \ApiQuery::getPricesFilterNew();
			$code = 1001;
			$message = "Success";
		}*/
		/* if($resourceType=='web'){
			include_once "/home/steelmin/public_html/api/storage/v2019/web/compare_mapping_post.php";
		}else{
			include_once "/home/steelmin/public_html/api/storage/v2019/compare_mapping_post.php";
		} */
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    } 
	
	public function getDateRangeFilter(Request $request)
    {
		$result = array();
		
		if($request->has('section') && !empty($request->input('section'))){
		    $section = $request->input('section');			
		}else{
			$code = 2013;
			$message = "Section type missing."; 
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');			
		}else{
			$code = 2013;
			$message = "ItemIds missing."; 
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		//print_r($itemID);
		///return $request->input('itemID');
		
		include_once($_ENV['COMMON_ROOT_PATH'].'/helper.php') ;
		$condition = "relation_id IN (". implode(',', $itemID) .")";
		$dateRange = getDateRange($section,$condition);
		$result['dateRange']=$dateRange;
		
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	//Saved comparison listing
	public function getCompareSavedList(Request $request)
    {      
	    $resourceType = "app";
		$filters = array();
		//return $request->all();
		
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($resourceType=='app' && $request->has('accessToken') && !empty($request->input('accessToken'))){
		    $auth = new authentication();	
			$token = $request->input('accessToken');
			$memid = $auth->authToken($token);	
		}elseif($resourceType=='web' && $request->has('memid') && !empty($request->input('memid'))){
			$memid = $request->input('memid');
			$auth = new authentication();
			$memid = $auth->authUserId($memid);//for web user
		}	
		$itemID=0;
		if($request->has('itemID') && !empty($request->input('itemID'))){
		    $itemID = $request->input('itemID');			
		}
		
		if($memid){
			$code = 1001;
			$message = "Success";
			$result = \ApiQuery::getPricesCompareSavedRows($resourceType, $memid, $itemID);
		}else{
			$code = 2013;
			$message = "User not found."; 
		}
	   		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function getHistoricalData(Request $request){
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
			 
		    $code = 1001;
			$message = "Success";
			if ($request->has('memid') && $request->input('memid')!=''){
				include_once "/home/steelmin/public_html/api/storage/v2019/web/history_prices_post.php";
			}else{
				include_once "/home/steelmin/public_html/api/storage/v2019/web/history_prices_pre.php";
			}
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result, "defaultItemsCount"=> 5));
	}
	
	public function compareUpdate(Request $request)
    {     
	    $resourceType = "app";
		$filters = array();
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		
		if($request->has('comparisonID') && !empty($request->input('comparisonID'))){
			$comparisonID = $request->input('comparisonID');			
		}else{
			$code = 2013;
			$message = "Comparison ID missing.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		if($request->has('compareName') && !empty($request->input('compareName'))){
		    $compareName = $request->input('compareName');			
		}else{
			$code = 2013;
			$message = "please enter compare title.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		$user_id=0;
		if($request->has('memid') && !empty($request->input('memid'))){
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
		}else{
			$code = 2013;
			$message = "memid missing.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}	
		
		if($user_id){
			
			$uData = array(
					"updatedOn"=>$GLOBALS['currDateTime'],
					///"memid"=>$memid,
					"compareName"=>$compareName
				);			
				
			DB::table('tbl_compare')
					->where("id" , "=" , $comparisonID )
					->update($uData) ;
			
			$code = 1001;
			$message = "Successfully Updated";
			$result['comparisonID'] = $comparisonID;
		}else{
			$code = 2100;
			$message = "Invalid User or User not found."; 
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }
	
	public function bySectionType(Request $request){
		
		$result = array();
		$resourceType='web';
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$deviceType='';
		if($request->has('deviceType'))
			$deviceType = strtolower($request->input('deviceType'));
		
		$user_id=0;
		if ($resourceType=='app' && $request->has('accessToken') && $request->input('accessToken')!='') {
			//$uemail = $request->input('email');//oldPassword
			$token = $request->input('accessToken');
			//$user = new User();
			$auth = new authentication();
			$user_id = $auth->authToken($token);
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}elseif ($resourceType=='web' && $request->has('memid') && $request->input('memid')!=''){
								
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
			if(!$user_id)
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}
		
		$accessType='pre';//for visitor///
		
		if($user_id){
			$user = new User($user_id, $this->appType);
			///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Prices');
			
			if ($isAccessible==-1) {
				$accessType = 'post';
			}else{
				$accessType = 'pre';
			}
		}
		$price_section_type='';
		if($request->has('price_section_type') && $request->input('price_section_type')!='')
			$price_section_type = strtolower($request->input('price_section_type'));
		else
			return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Invalid Price Section.")));
		
		
		$filename = "https://www.steelmint.com/v2019/Json/price_section_type/".$accessType."_".$deviceType."_".$price_section_type.".json"; 
		
		if($accessType == 'post'){
			$result = file_get_contents($filename);	
			$p_array = json_decode($result,true); 
			$common = new Common();
			$c = $common->getBookmarked($user_id,$p_array, true);
			$result = json_encode($c);
			return $result;
		}else{
			return file_get_contents($filename);	
		}			
	}
}
