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

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

use App\Traits\ReferenceData;

class LogisticsController extends Controller
{
	use ReferenceData {
        getReferenceData as protected refData;
    }
	
    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 logisticSectionStatusForAPP(Request $request)
    {
		$resourceType = "app";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$token='';
		if($request->has('accessToken')){
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token);
		}
		//
		//$url = "http://50.116.49.118/theitbooth/logistics?deviceType=ios&mobile=1&accessToken=".$token;
		$url = BASEURL."logistics?deviceType=ios&mobile=1&accessToken=".$token;
		if($user_id){
			$user = new User($user_id, $this->appType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Logistics');//Railway_Movement
			
			if ($isAccessible==-1) {
				$logisticsSectionStatus = "active";
			}else{
				$logisticsSectionStatus = "upgrade";
			}			
		}else{
			$logisticsSectionStatus = "upgrade";
		}
		
		
		$result['logisticsSectionStatus'] = $logisticsSectionStatus;
		$result['logisticsSectionUrl'] = $url;
		
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function getRailwayMovement(Request $request)
    {      
		
		$result = array();
		$resourceType = "web";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if ($request->has('commodityID')){
			$commodityID = $request->input('commodityID');
			$filters['commodityID'] = $commodityID;
		}/* else{
			$code = 2014;
			$message = "Invalid! commodity missing.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		} */
		
		if ($request->has('regionID')){
			$regionID = $request->input('regionID');
			if(!empty($regionID))$filters['regionID'] = $regionID;
		}/*else{
			$code = 2014;
			$message = "Invalid! region missing.";			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}*/
		
		$onDate='';
		if ($request->has('onDate')){
			$onDate = strtolower($request->input('onDate'));
			$filters['onDate'] = $onDate;
		}
		
		$isDownload=0;
		if ($request->has('isDownload')){
			$isDownload = $request->input('isDownload');			
		}
		
		$filters['isDownload'] = $isDownload;
		
		if ($request->has('debug')){
			$filters['debug'] = $request->input('debug');
		}
		
		$code = 1001;				
		$message = "Success";
		$accessType='pre';//for visitor/upgrade///		
		
		$user_id=0;
		
		$token='';///call from mobileapp as iframe
		//if($request->has('accessToken') && ($request->input('accessToken')!='null' || $request->input('accessToken')!=null)){
		if($request->has('accessToken') && $request->has('accessToken')!=''){
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token);
			$resourceType='app';
		}elseif ($request->has('memid') && $request->input('memid')!=''){								
			
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
		}
		//echo "userid:" . $user_id; dd();
		//return $request->input('accessToken');
		///
		if (($request->has('memid') && $request->input('memid')!='') || $token!=''){
			
			if ($user_id) {
				
				if($user_id){
					$user = new User($user_id, $this->appType);
					///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
					$isAccessible =  $user->isAccessible($resourceType, $section='Logistics');//Railway_Movement
					
					if ($isAccessible==-1) {
						$accessType = 'post';
					}else{
						$accessType = 'pre';
					}
				}
				
			}else{
				$code = 2013;
				$message = "Unauthorized action.";
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
		}
		
		//if($isDownload==1 && $accessType=='pre'){
		if($accessType=='pre'){
		    if($isDownload==1){
    			$code = 2013;
    			$message = "Unauthorized action.";
    			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		    } else {
        		$result = \ApiQuery::getRailwayMovementRows( $user_id, $resourceType, $filters, $accessType, $this->appType);
		    }
		} else
		    $result = \ApiQuery::getRailwayMovementRows( $user_id, $resourceType, $filters, $accessType, $this->appType);
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }  	
	
	public function getRailwayMovementFilter(Request $request)
    { 
		$result = array();
		$resourceType = "web";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/RailwayMovementFilter.php";
		
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function getVesselLineupFilter(Request $request)
    { 
		$result = array();
		$resourceType = "web";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
		    
			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
				include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/VesselLineupFilter_CM.php";
			} else 
				include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/VesselLineupFilter.php";
		} else 
			include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/VesselLineupFilter.php";
		
		$ids = array();
		$excel_upoad_date_time_arr = DB::table('tbl_logistic_data')->select("excel_upoad_date_time")->orderBY('id','desc')->first();
		
		$excel_upoad_date_time = $excel_upoad_date_time_arr["excel_upoad_date_time"];
		
		/*$tbl_logistic_arr = DB::table('tbl_logistic_data')->where("excel_upoad_date_time","=",$excel_upoad_date_time)->groupBy('selected_country')->groupBy('commodity')->get();
	
		
		$commodities=array();
		foreach($tbl_logistic_arr as $k=> $v){
			$result['region'][] = array(
									"isSelectable" => "y",
									"id" => $v['selected_country'],
									"name" => $v['selected_country']
								 );
			 
			$commodities[$v['commodity']] = $v['commodity'];
		}
		
		foreach($commodities as $k=> $v){
			$result['commodities'][] = array(
										"isSelectable" => "y",
										"id" => strtoupper($v),
										"name" => strtoupper($v)
									);
		}
		
		
		$result["statusFilterValues"] = array(
			"Anchorage","Berth", "Expected"
        );
		$result["movementFilterValues"] = array(
			"Import","Export","Coastal Load"
        );*/
		
		$result['excel_upoad_date_time'] = $excel_upoad_date_time;

		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function getVesselLineup(Request $request)
    {      
		$result = array();
		$resourceType = "web";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$filters= array();
		if ($request->has('commodity')){
			$commodity = $request->input('commodity');
			$filters['commodity'] = $commodity;
		}
		
		if ($request->has('region')){
			$region = $request->input('region');
			$filters['region'] = $region; 
		}
		$isCoalmint=0;
		if ($request->has('isCoalmint')){
			$isCoalmint = $request->input('isCoalmint');
			$filters['isCoalmint'] = $isCoalmint; 
		}
		
		///$Movement='';
		if ($request->has('movement')){
			$movement = $request->input('movement');
			$filters['movement'] = $movement;
		}
		
		if ($request->has('status')){
			$status = $request->input('status');
			$filters['status'] = $status;
		}
		
		$isDownload=0;
		if ($request->has('isDownload')){
			$isDownload = $request->input('isDownload');			
		}
		
		$filters['isDownload'] = $isDownload;
		
		if ($request->has('debug')){
			$filters['debug'] = $request->input('debug');
		}

		if($request->has('filters') && !empty($request->input('filters'))){
		    //echo "yes";
		    $filters = $request->input('filters');
		   // print_r($filters);
			if( isset($filters['app_type']) && $filters['app_type'] == 'CM')
				$this->appType = "CM";
		}

		
		$code = 1001;				
		$message = "Success";
		$accessType='pre';//for visitor/upgrade///		
		$user_id=0;
		$token='';///call from mobileapp as iframe
		if($request->has('accessToken')){
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token);
		}elseif ($request->has('memid') && $request->input('memid')!=''){								
			
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
		}
		///
		if (($request->has('memid') && $request->input('memid')!='') || ($request->has('accessToken') && $request->input('accessToken')!='')){	
			if ($user_id) {
				
				if($user_id){
					$user = new User($user_id, $this->appType);
					///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
					$isAccessible =  $user->isAccessible($resourceType, $section='Logistics');
					
					if ($isAccessible==-1 || $isCoalmint==1) {
						$accessType = 'post';
					}else{
						$accessType = 'pre';
					}
				}
				
			}else{
				$code = 2013;
				$message = "Unauthorized action.";
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
		}
		
		if($isDownload==1 && $accessType=='pre'){
			$code = 2013;
			$message = "Unauthorized action.";
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		$result = \ApiQuery::getVesselLineupRows( $user_id, $resourceType, $filters, $accessType, $this->appType);
		
		if( count($result) == 0)
		    $message = "No Record Found.";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }  	
	
	public function getVesselFreightFilter(Request $request)
    { 
		$result = array();
		$resourceType = "web";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('filters') && !empty($request->input('filters'))){
		    $filters = $request->input('filters');
		    
			if( isset($filters['app_type']) && $filters['app_type'] == 'CM'){
				include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/VesselFreightFilter_CM.php";
			} else 
				include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/VesselFreightFilter.php";
		} else 
			include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/VesselFreightFilter.php";




//		include_once "/home/steelmin/public_html/api/storage/v2019/Json/Web/VesselFreightFilter.php";
		
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function getVesselFreight(Request $request)
    {      
		$result = array();
		$resourceType = "web";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$filters= array();
		if ($request->has('commodity')){
			$commodity = $request->input('commodity');
			$filters['commodity'] = $commodity;
		}
		
		/* if ($request->has('regionID')){
			$regionID = $request->input('regionID');
			$filters['regionID'] = $regionID;
		} */
		
		///$Movement='';
		if ($request->has('loadCountry')){
			$loadCountry = $request->input('loadCountry');
			$filters['loadCountry'] = $loadCountry;
		}
		
		if ($request->has('unLoadCountry')){
			$unLoadCountry = $request->input('unLoadCountry');
			$filters['unLoadCountry'] = $unLoadCountry;
		}
		
		$isDownload=0;
		if ($request->has('isDownload')){
			$isDownload = $request->input('isDownload');			
		}
		
		$filters['isDownload'] = $isDownload;
		
		if ($request->has('debug')){
			$filters['debug'] = $request->input('debug');
		}

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

		
		$code = 1001;				
		$message = "Success";
		$accessType='pre';//for visitor/upgrade///		
		$user_id=0;
		$token='';///call from mobileapp as iframe
		if($request->has('accessToken')){
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token);
		}elseif ($request->has('memid') && $request->input('memid')!=''){								
			
			$memid = $request->input('memid');
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
		}
		//
		if (($request->has('memid') && $request->input('memid')!='') || ($request->has('accessToken') && $request->input('accessToken')!='')){		
			if ($user_id) {
				
				if($user_id){
					$user = new User($user_id, $this->appType);
					///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
					$isAccessible =  $user->isAccessible($resourceType, $section='Logistics');
					
					if ($isAccessible==-1) {
						$accessType = 'post';
					}else{
						$accessType = 'pre';
					}
				}
				
			}else{
				$code = 2013;
				$message = "Unauthorized action.";
				return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
			}
		}
		
		if($isDownload==1 && $accessType=='pre'){
			$code = 2013;
			$message = "Unauthorized action.";
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
		}
		
		$result = \ApiQuery::getVesselFreightRows( $user_id, $resourceType, $filters, $accessType, $this->appType);
		
		if( count($result) == 0)
		    $message = "No Record Found.";
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }
	
	public function getVesselFreightGraph(Request $request)
    {      
		$result = array();
	    $resourceType = "web";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));		
		
		if ($request->has('itemID')) {
            $relation_id = $request->input('itemID') ;
        }else{
			return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Invalid ItemId.")));
		}
		
		$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.")));
		}
		
		if($user_id){
			$user = new User($user_id, $this->appType);
			///$isAccessible = $user->getTakenServicesByUser($item='prices', $at_place=$resourceType);
			$isAccessible =  $user->isAccessible($resourceType, $section='Logistics');//Railway_Movement
			
			if ($isAccessible==-1) {
				$randNum = 1;
			}else{
				$randNum = mt_rand(111, 111111) / 100;
			}
		}

        if( $request->has('assesment')) {
            $assesment = $request->input('assesment') ;
        }
		
		if( $request->has('currencyName')) {
            $currency = $request->input('currencyName') ;
        }
		
		$requiredfor='';
		$_logStartDate='';
		if( $request->has('requiredFor')) {
            $requiredfor = $request->input('requiredFor') ;
        }
		
		$dateFilter = array();
		
		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;			
		}
		
		$code = 1001;
		$message = "Success";
		$result =  \ApiQuery::getVesselFreightPricesByWeeksForGraph($relation_id, $randNum, $dateFilter);
		
		$res = array("status"=>array("code" => $code, "message" => $message), "data"=> $result);
		
	    return new JsonResponse($res);
    }
	
}
