<?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;
use Cookie;

class PriceSpreadController 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 getPriceSpread(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');
			
			///cphrase code
			if((isset($filters['searchTerms']) && $filters['searchTerms']!='')){
				$common = new Common();
				$innerFilterCond = $common->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');	
		
		if(isset($filters['price_section_type'])){
			if( isset($filters['deviceType']) && $filters['deviceType'] == 'ios')
				$offset = ($pageValue-1)* 8;
			else
				$offset = ($pageValue-1)* 11;	
		}elseif(isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard') {
		    $offset = ($pageValue-1)* 10;		
		} else
			$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,$this->appType);
			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');
			    $memid = htmlentities($request->input('memid'), ENT_QUOTES);

                if( !is_numeric($memid) ){
                    return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
                }
			
			$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');
			$isAccessible =  $user->isAccessible($resourceType,$section='Prices','','','',$filters['selected_market']);
			
			if ($isAccessible==-1) {
				$accessType = 'post';
			}else{
				$accessType = 'pre';
			}
		}		
		
		if($pageValue>1 || count($filters)>0){
			$result = \ApiQuery::getPriceSpreadRows($user_id, $source, $resourceType, $type='', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);			
		}else {/// data from json array file 		
			$result = \ApiQuery::getPriceSpreadRows($user_id, $source, $resourceType, $type='default', $filters, $accessType,DEFAULT_PRICES_LIMIT, $offset, $this->appType, $currency);
		}

		$code = 1001;				
		$message = "Success";

        if(isset($filters['renderAt']) && $filters['renderAt'] == 'new_dashboard') {
            $ex = $result;
            $result = array();
            $result = $ex["dataValue"];
            $cntValue = $ex["cntValue"];
        } else {
            $cntValue = 0;
        }

		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result, "defaultItemsCount"=> 5, "cntValue"=> $cntValue));
    }
    
    public function getPriceSpreadDetails(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,$this->appType);	
		}elseif($resourceType=='web' && $request->has('memid') && !empty($request->input('memid'))){
			//$memid = $request->input('memid');
			    $memid = htmlentities($request->input('memid'), ENT_QUOTES);

                if( !is_numeric($memid) ){
                    return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
                }
			
			$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');
			$isAccessible =$user->isAccessible($resourceType,$section='Prices','','','',$filters['selected_market']);
			if($filters['selected_market']==''){
                    $market_list = DB::table('tbl_op_commodity_master')
                    ->join('tbl_spread_master', 'tbl_op_commodity_master.id', '=', 'tbl_spread_master.id2') 
                    ->where('tbl_spread_master.id', '=', $itemID) 
                    ->select('tbl_op_commodity_master.f_market')                     
                    ->first();
                    if(!empty($market_list['f_market']))
                       $isAccessible = $user->isAccessibleMarketWise($market_list['f_market']);
            }
			
			if ($isAccessible==-1) {
				$accessType = 'post';
			}
		}
		if ($request->has('requiredFor') && $request->input('requiredFor')=='home_pre_login'){
			$accessType = 'post';
			/* echo "<pre>";
			print_r($filters); */
		}
		
		$resultDetails = \ApiQuery::getPriceSpreadRows($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 getPriceSpreadGraph(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='';
		$filters=array();
		
		//for selected_market		
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters'); 
		    $selected_market = $filters['selected_market'];
        }	
		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,$this->appType);
			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');
			    $memid = htmlentities($request->input('memid'), ENT_QUOTES);

                if( !is_numeric($memid) ){
                    return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
                }

			
			$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'){
			if( $this->appType = 'CM'){
				/* $i_id = 75;
				$priceType = "fob";
				$assesment = 'W'; */	
				$i_id = 5355;	
				$priceType = "fob";
				$assesment = 'D';
			} 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'].'/mappNewSpread.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;			
		}

		if ($request->has('source') && $request->input('source')=='newsLetter'){
			$dateFilter['source'] = $request->input('source');
			$dateFilter['fromDate']  = date('Y-m-d', strtotime('-12 months'));
			$dateFilter['toDate']  = date('Y-m-d');
		}
		
		$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');
				
				$isAccessible =  $user->isAccessible($resourceType, $section='Price Graph','','','',$selected_market);
				if($selected_market==''){
                  $market_list = DB::table('tbl_op_commodity_master')
                    ->join('tbl_spread_master', 'tbl_op_commodity_master.id', '=', 'tbl_spread_master.id2') 
                    ->where('tbl_spread_master.id', '=', $relation_id) 
                    ->select('tbl_op_commodity_master.f_market')                     
                    ->first();
                    if(!empty($market_list['f_market']))
                       $isAccessible = $user->isAccessibleMarketWise($market_list['f_market']);
                }
			
            
				//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,$filters);
					
				}
			}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,$filters);
			}
		}else{
			$result = getGraphDataForIdNew($resourceType, $user_id , $relation_id , $price_type_prefix , $assesment, $appType=$this->appType, $currency, $requiredfor, $_logStartDate, $dateFilter,$f_heading,$filters);
		}
				
		$res = array("status"=>array("code" => $code, "message" => $message), "data"=> $result);
		
		$res["currency"] = $currency;
		
		if($requiredfor=='comparison'){
			$res["startDate"] = $_logStartDate;
		}
	    return new JsonResponse($res);
    }
}
