<?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 Prices1Controller 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');		
        }
    }
	
	public function getPrices(Request $request)
    {      
		$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');
		
		$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;		
		
		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);
			if ($isAccessible==-1) {
				$accessType = 'post';
			}else{
				$accessType = 'pre';
			}
		}
		
		if($pageValue>1 || count($filters)>0){			
			$result = \ApiQuery::getPricesRows($memid, $source, $resourceType, $type='', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);			
		}else {/// data from json array file 		
			$result = \ApiQuery::getPricesRows($memid, $source, $resourceType, $type='default', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);
		}
		
		$code = 1001;				
		$message = "Success";
			
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result, "defaultItemsCount"=> 5));
    }  
	
    public function getPriceDetails(Request $request){
		$resourceType = "app";
		$filters = array();
		if($request->has('filters') && !empty($request->input('filters')))
		    $filters = $request->input('filters');
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		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');;
			}
		}else{
			$code = 2013;
			$message = "Invalid! itemID missing.";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		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
		}	
		
		$currency = '';
		if( $request->has('currencyName')) {
            $currency = $request->input('currencyName') ;
        }
		
		$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);
			if ($isAccessible==-1) {
				$accessType = 'post';
			}
		}
		
		$resultDetails = \ApiQuery::getPricesRows($memid, $source='', $resourceType, $type='', $filters, $accessType,1, $offset=0, $this->appType, $currency);
		if(count($resultDetails)>0){
			$result = $resultDetails[0];
		}
		$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'));
		
		
		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.")));
		}
				
		include($_ENV['COMMON_ROOT_PATH'].'/mappNew.php') ;

		$user_id = '' ;
		$relation_id = $id ;
		$price_type_prefix = 'f';
		$assesment = 'W';
		$currency = '';
		
		if ($request->has('itemID')) {
            $relation_id = $request->input('itemID') ;
        }else{
			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') ;
        }
		
		$code = 1001;
		$message = "Success";
		$result = getGraphDataForId($user_id , $relation_id , $price_type_prefix , $assesment, $appType=$this->appType, $currency);
		
	    return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    } 
	
	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";
		} */
		
		$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($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)));
		}
		
		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(!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 = '' ;
		$relation_id = $id ;
		$price_type_prefix = 'f';
		$assesment = '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('assesment')) {
            $assesment = $request->input('assesment') ;
        }
		
		if( $request->has('currencyName')) {
            $currency = $request->input('currencyName') ;
        }		
		
		$code = 1001;
		$message = "Success";
		$result['item1'] = getGraphDataForId($user_id , $relation_id1 , $price_type_prefix1 , $assesment, $appType=$this->appType, $currency);
		$result['item2'] = getGraphDataForId($user_id , $relation_id2 , $price_type_prefix2 , $assesment, $appType=$this->appType, $currency);
		
	   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($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)));
		}
		
		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(!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');			
		}
		$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 . ".png", $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"=>$item1['commodityID'],
					"commodityID2"=>$item2['commodityID'],
					"regionID1"=>$item1['regionID'],
					"regionID2"=>$item2['regionID'],
					"relationID1"=>isset($item1['relationID'])?$item1['relationID']:'',
					"relationID2"=>isset($item2['relationID'])?$item2['relationID']:'',					
					"2ndLevel1"=>isset($item1['2ndlevel'])?$item1['2ndlevel']:'',
					"2ndLevel2"=>isset($item2['2ndlevel'])?$item2['2ndlevel']:'',
					"fromDate"=>$fromDate,
					"toDate"=>$toDate,
					"assessmentType"=>$assessmentType
				);
				
				//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 = 2013;
			$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($regionID==''){
			$code = 9999;
			$message = "Please select region."; 
		}elseif($tradeType==''){
			$code = 9999;
			$message = "Please select tradeType."; 
		}else{
			$result = \ApiQuery::getPricesFilter($section, $tradeType, $regionID, $this->appType);
			$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));
    } 
	
	//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($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));
	}
	

}
