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

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

use App\Traits\ReferenceData;

class userController extends Controller
{ 
	//use ReferenceData;
	use ReferenceData {
        getReferenceData as protected refData;
        getReferenceDataFilter as protected refDataFilter;
    }

    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 getArray(Request $request){
		
		$resourceType = "app";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$place='';$itemType=''; $section='';
		if($request->has('place'))
			$place = strtolower($request->input('place'));
		
		if($request->has('itemType'))
			$itemType = strtolower($request->input('itemType'));
		
		if($request->has('section'))
			$section = strtolower($request->input('section'));
		
		if($resourceType=='web' && $section=='event'){
			$resultset = $this->refData($resourceType, $itemType, $section='event', $place="WEB_EVENTS_LANDING_LISTING_CMBBOX", $otherCondition='');		
			$result = $resultset['WEB_EVENTS_LANDING_LISTING_CMBBOX'];
		}elseif($resourceType=='web' && $section=='tender'){
			$resultset = $this->refData($resourceType, $itemType, $section);		
			$result = $resultset['WEB_TENDER_LISTING_FILTER'];
		}elseif($resourceType=='web' && $section=='insight'){
			$resultset = $this->refData($resourceType, $itemType, $section);		
			$result = $resultset['WEB_INSIGHT_LANDING_LISTING_CMBBOX'];
		}elseif($resourceType=='web' && $section=='price'){
			$resultset = $this->refData($resourceType, $itemType, $section);		
			$result = $resultset['WEB_PRICE_LANDING_LISTING_CMBBOX'];
		}elseif($resourceType=='web' && ($place!='' || $itemType!=''))
			$result = $this->refDataFilter($resourceType, $itemType, $section, $place);		
		else
			$result = $this->refData($resourceType);		
		//return A::calc($v);
		return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> $result));
	}
	
	public function getPackageDetails(Request $request){
		
		$resourceType = "app";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		//if(!$request->has('packageID')){
		if(!$request->has('itemID')){
			 return new JsonResponse(array("code" => 2001, "message" => "invalid package"));
		}
		
		//$packageID = $request->input('packageID');
		$packageID = $request->input('itemID');
		if($request->has('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")));
                }
			
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
		}elseif($request->has('accessToken')){
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token);
		}
		
		$common = new Common();
		$result = $common->getPackagesDetail($packageID, $memid);
				
		//return A::calc($v);
		return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> $result));
	}
	
	public function index()
    {      
	   $result = array();
	   $result = $this->referenceDataArr;
	   //$a = $this->getReferenceData();
	   $dbresult = DB::table('tbl_companytype')
				->select('id','short_comptype as name' )				
				->get();
		foreach($dbresult as $cType){
			$result['companyType'][$cType["id"]] = $cType["name"];
		}
	   return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> $result));
    }  
	
	public function alerts(Request $request)
    {      
	   $result = array();
	   
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
			$source = $request->input('source');//Tender/Prices

			$itemId = $request->input('itemId');
			$mediumList = $request->input('mediumList');//["email"  , "sms" ]
			$xDaysBefore = $request->input('xDaysBefore');
			$action = $request->input('action'); 
			$accessToken = $request->input('accessToken');
		}
		$code = 1001;
		$message = "Alert Set Successfully";
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    } 
	
	public function removeBookmark(Request $request)
    {      
	    $result = array();
	    $accessToken = $request->input('accessToken');
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
			$source = $request->input('source');//price/insights/tender

			$itemId = $request->input('itemId');
			$section = $request->input('section'); //bookmark/compare/portfolio/alerts
			switch($section){
				case "bookmark":
					switch($source){
						case "price":
						break;
						case "insights":
						break;
						case "tender":
						break;
					}
				break;
				case "compare":
					switch($source){
						case "price":
						break;
						case "insights":
						break;
						case "tender":
						break;
					}
				break;
				case "portfolio":
					switch($source){
						case "price":
						break;
						case "insights":
						break;
						case "tender":
						break;
					}
				break;
				case "alerts":
					switch($source){
						case "price":
						break;
						case "insights":
						break;
						case "tender":
						break;
					}
				break;
			}
			
			$code = 1001;
			$message = "Successfully Saved";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}
		
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    } 
	//Add bookmark -
	public function addBookmark(Request $request)
    {      
	    $result = array();
	    $accessToken = $request->input('accessToken');
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
			$source = $request->input('source');//price/insights/tender

			$itemIds = $request->input('itemIds');
			///$section = $request->input('section'); //bookmark/compare/portfolio/alerts
			switch($source){
				case "price":
				break;
				case "insights":
				break;
				case "tender":
				break;
			}
			
			$code = 1001;
			$message = "Successfully Bookmarked";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}
		
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }
	//Show more/less Like this - insight
	public function showSimilar(Request $request)
    {      
	    $result = array();
	    $accessToken = $request->input('accessToken');
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
			$source = $request->input('source');//price/insights/tender

			$itemIds = $request->input('itemIds');
			$type = $request->input('type'); //more/less
			switch($source){				
				case "insights":
				break;
				case "tender":
				break;
			}
			
			$code = 1001;
			$message = "Successfully Saved";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}
		
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }
	
	
	public function portfolioAddItem(Request $request)
    {      
	    $result = array();
	    //$accessToken = $request->input('accessToken');
		$resourceType = "app";
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		if($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")));
                }
			
			//$memid = _encrypt_decrypt($action='decrypt', $memid);
			$auth = new authentication();
			$user_id = $auth->authUserId($memid);//for web user
		}elseif($resourceType=='app' && $request->has('accessToken') && !empty($request->input('accessToken'))){
			$token = $request->input('accessToken');
			$auth = new authentication();
			$user_id = $auth->authToken($token);
		}
		
		if(!$user_id){
			$code = 2001;
			$message = "Invalid  User";
		}else{
		
			$section = $request->input('section');//price/insights/tender

			///$itemID = $request->input('itemID');
			///$section = $request->input('section'); //bookmark/compare/portfolio/alerts
			switch($section){
				case "price":
				case "prices":
					$rows_input = $request->input('itemID');
					//print_r($rows_input);
					// if($request->has('accessToken'))
						// $rows = json_decode(stripcslashes($rows_input), true);
					// else
						$rows = $rows_input;
					
					foreach($rows as $_row){
						$row_id = $_row['rowID'];
						$prices_col = $_row['pricesCol'];
						$flag = $_row['flag'];
						if($flag==0){
							DB::table('tbl_user_portfolio')
							->where('type', '=', 'prices' )
							->where('user_id', '=', $user_id )
							->where('prices_col', '=', $prices_col )
							->where('appType', '=', $this->appType )
							->where('row_id', '=', $row_id )
							->delete();	
							$message = "Successfully removed from Portfolio";
						}else{
							DB::table('tbl_user_portfolio')
							->where('type', '=', 'prices' )
							->where('user_id', '=', $user_id )
							->where('prices_col', '=', $prices_col )
							->where('appType', '=', $this->appType )
							->where('row_id', '=', $row_id )
							->delete();
							
							$ipAddress = $_SERVER['REMOTE_ADDR'];	
							DB::table('tbl_user_portfolio')->insert([ 'ip' => $ipAddress,
							'user_id' => $user_id,
							'type' => 'prices',
							'prices_col' => $prices_col,
							'appType' => $this->appType,
							'row_id' => $row_id,
							'created_on' => $GLOBALS['currDateTime']]);
							
							$message = "Successfully added to Portfolio";
						}
					}
				break;
				case "insights":				
				case "tender":
					/* $category = !empty($request->input('category'))?$request->input('category'):'';
					$country = !empty($request->input('country'))?$request->input('country'):'';
					$lead_type = !empty($request->input('lead_type'))?$request->input('lead_type'):'';
					
					DB::table('tbl_user_portfolio')
						->where('type', '=', $type)
						->where('user_id', '=', $user_id)
						->where('appType', '=', $appType )
						->delete();
					
					$ipAddress = $_SERVER['REMOTE_ADDR'];	
					DB::table('tbl_user_portfolio')->insert([ 'ip' => $ipAddress,
					'user_id' => $user_id,
					'type' => $type,
					'category' => $category,
					'country' => $country,
					'row_id' => 0,
					'lead_type' => $lead_type,
					'appType' => $appType,
					'created_on' => $GLOBALS['currDateTime']]); */
				break;
			}
			
			$code = 1001;
		//	$message = "Successfully Saved";
		}
		
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }
	
	public function addPreferences(Request $request)
    {      
		$resourceType = "app";
		$user_id = 0;
		
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if(!$request->has('section')){
			return new JsonResponse(array("code" => 2001, "message" => "invalid section!"));
		}
		$section = $request->input('section');//"Tender/Insight/Intel/all",
		
		$commodityID=array();
		if($request->has('commodityID')){
			$commodityID = $request->input('commodityID');
		}
		$regionID=array();
		if($request->has('regionID')){
			$regionID = $request->input('regionID');
		}
		
		if ($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("code" => 2100, "message" => "Unauthorized action."));
		}elseif ($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("code" => 2100, "message" => "Unauthorized action."));
		}
		if($user_id){
			///$itemIds = $request->input('itemIds');		
			//$channel = $request->input('channel'); //["whatsapp", "fb"]
			switch($section){
				case "price":
				break;
				case "insights":
				break;
				case "intel_insight":
				case "tender":
					
					DB::table('tbl_user_portfolio')
						->where('type', '=', $section)
						->where('user_id', '=', $user_id)
						->where('appType', '=', $this->appType )
						->delete();
					
					$ipAddress = $_SERVER['REMOTE_ADDR'];	
					DB::table('tbl_user_portfolio')->insert([ 'ip' => $ipAddress,
					'user_id' => $user_id,
					'type' =>  $section,
					'commodityId' => implode(',',$commodityID),
					'regionId' => implode(',',$regionID),
					'row_id' => 0,
					///'lead_type' => $lead_type,
					'appType' => $this->appType,
					'created_on' => $GLOBALS['currDateTime']]); 
				break;
			}
			
			$code = 1001;
			$message = "Successfully Saved";
		}else{
			//return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
			$code = 2100;
			$message = "Unauthorized action";
		}
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	   //return new JsonResponse(array("code" => $code, "message" => $message));
    }
	
	public function getPreferences(Request $request)
    {      
		$resourceType = "app";
		$user_id = 0;
		
		$result = (object)array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if(!$request->has('section')){
			return new JsonResponse(array("code" => 2001, "message" => "invalid section!"));
		}
		$section = $request->input('section');//"Tender/Insight/Intel/all",
				
		if ($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("code" => 2100, "message" => "Unauthorized action."));
		}elseif ($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("code" => 2100, "message" => "Unauthorized action."));
		}
		if($user_id){
		
			$dbresult = DB::table('tbl_user_portfolio')
				->select('commodityID', 'regionID', 'type' )				
				->where('type', '=',  $section)
				->where('user_id', '=', $user_id)
				->where('appType', '=', $this->appType )
				->orderBy('id' , 'desc')
				->first();
			
			if(count($dbresult)>0){
				//$result[$dbresult['type']] = array(
				$commodityId = explode(',', $dbresult['commodityID']);
				$regionId = explode(',', $dbresult['regionID']);
				$commodityIDArr=array();
				$regionIDArr=array();
				foreach($commodityId as $id){
					$commodityIDArr[] = (int)$id;
				}
				foreach($regionId as $id){
					$regionIDArr[] = (int)$id;
				}
				
				$result = array(
					"commodityID" => $commodityIDArr,
					"regionID" => $regionIDArr,
				);
			}
			
			$code = 1001;
			$message = "Success";
			
			return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> $result));
		}else{
			return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
		}	  
    }
	
	public function download(Request $request)
    {      
		$resourceType = "app";
		$user_id = 0;
		
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$section='';
		if($request->has('section'))
			$section = strtolower($request->input('section'));
		
		if($request->has('company'))
			$company = strtolower($request->input('company'));
		
		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("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("code" => 2100, "message" => "Unauthorized action."));
		}
		
		switch($section){
			case "price":				
			break;
			case "report":
				if($request->has('itemID') && $request->input('itemID')!=''){
					$itemID = $request->input('itemID');
					$fDate = $request->input('fDate');
				
					$user = new User($user_id, $this->appType);
					$isAccessible = $user->getTakenServicesByUser($item=$itemID, $at_place='reports', $fDate);
					if ($isAccessible==-1) {
						$result['path'] = "https://www.steelmint.com/reports/Iron_Ore_Insight_28_02_2019.pdf";
					}else{
						return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
					}	
				}				
			break;
			case "tender":
				if($request->has('itemID') && $request->input('itemID')!=''){
					$itemID = $request->input('itemID');
				
					$user = new User($user_id, $this->appType);
					$isAccessible = $user->getTakenServicesByUser($item=$itemID, $at_place='tenders');
					if ($isAccessible==-1) {
						$result['path'] = "https://www.steelmint.com/reports/Iron_Ore_Insight_28_02_2019.pdf";
					}else{
						return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
					}	
				}
			break;
			case "invoice":
				if($request->has('invNo') && $request->input('invNo')!=''){
					$inv_no=$request->input('invNo');
				
					if($user_id){
						if ($company=='events' || $company=='event') {
							$result['path'] = "https://www.steelmint.com/invoices/multiform/preview.php?inv_no=".$inv_no;
						}else{
							$result['path'] = "https://www.steelmint.com/invoices/preview.php?inv_no=".$inv_no;
						}
					}
					
					$code = 1001;
					$message = "Success";
			
				}else{
					return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Invalid invoice")));
				}
			break;
		}
	
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }
	
	public function alertsListing(Request $request)
    {      
		$result= array();
		if ($request->has('accessToken') && $request->input('accessToken')!='') {
			$source = $request->input('source');//price/insights/tender

			switch($source){
				case "tenders":
				case "tender":
					$result['tender'] = array(
						array(
							'itemId'=>10,
							'title'=>"Iron Ore Tenders",
							//'medium'=>array('sms','push','wa')
						),
						array(
							'itemId'=>1,
							'title'=>"Billet Tenders",
							//'medium'=>array('sms','push','email')
						)
					);
				break;
				case "prices":
					$result['prices'] = array(
						array(
							'itemId'=>1003,
							'title'=>"Iron Ore prices",
							//'medium'=>array('sms','push','wa')
						),
						array(
							'itemId'=>22,
							'title'=>"Billet prices",
							//'medium'=>array('sms','push','email')
						)
					);
				break;
			}
			
			$code = 1001;
			$message = "Success";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		}
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }
	
	public function getFAQ()
    {      
	    $result = array();
		include_once "/home/steelmin/public_html/api/storage/v2019/faqs.php";
	    
		$code = 1001;
		$message = "Successfully Saved";
		
	   //, "data"=> $result;
	    return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }	
	
	public function notificationDetails(Request $request)
    {      
		$result = array();
		$resourceType = "app";
		$user_id = 0;
		$gcm_id ==0;
		
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		
		if ($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("code" => 2100, "message" => "Unauthorized action."));
			
		}elseif ($request->has('deviceID') && $request->input('deviceID')!=''){//visitor
								
			$deviceID = $request->input('deviceID');
			
			$sel_admob=DB::table('gcm_device')
						->select('id')	
						->where("device" , "=" , $request->input('deviceType'))
						->where("device_id" , "=" , $deviceID )
						->where("appType" , "=" , $this->appType )
						->first();
			
			
			if(count($sel_admob)>0)
				$gcm_id = $sel_admob['id'];///use this
		}
		///echo "user_id : ".$user_id;
		if($user_id){
			$sel_admob=DB::table('gcm_device')
					->select('id')	
					->where("device" , "=" , $request->input('deviceType'))
					->where("user_id" , "=" , $user_id )
					->where("appType" , "=" , $this->appType )
					->orderBy('id' , 'desc')
					->first();
					
			if(count($sel_admob)>0)
				$gcm_id = $sel_admob['id'];///use this
		}
		///echo "<br>gcm_id : ".$gcm_id;
		$notifications_ids = 0;
		if($gcm_id){///name SEPARATOR '-'
			//DB::enableQueryLog(); //dd(DB::getQueryLog());	
			$notifications=DB::table('tbl_sent_notifications')
					->select(DB::raw("GROUP_CONCAT(f_notification_list_id) as `ids`"))
					->where("f_gcm_tbl_id" , "=" , $gcm_id )
					->where("read_status" , "=" , 0 )
					->orderBy('id' , 'desc')
					->first();
					
			if(count($notifications)>0)
				$notifications_ids = $notifications['ids'];///use this
		}else{
			return new JsonResponse(array("code" => 1011, "message" => "Unauthorized action, device not registered."));
		}
		///echo "<br>notifications_ids : ".$notifications_ids;
		$dbresult = DB::table('tbl_notification_list')
				->select('*' )				
				->orderBy('sent_at' , 'desc')
				->whereIn('id', explode(',',$notifications_ids) )
				->limit(30)
				->get();
		
		if (count($dbresult) > 0){
			foreach($dbresult as $logs){
				$item = array(
					'notificationTitle' => htmlentities($logs['notification_title'], ENT_QUOTES),
					'notificationDescription' => htmlentities($logs['description'], ENT_QUOTES),
					'priceType' => $logs['price_type'],
					'category' => $logs['category'],
					'sent_at' => $logs['sent_at'],
					'itemID' => $logs['itemID'],
					'timeline' => $logs['timeline'],
					'promotion_url' =>$logs['f_url'],
					'icon' => url('/')."/uploads/notification/".$logs['category'].".png"
				);
				$result[] = $item;
			}
		}
	    /* array (
				  'id' => '24080',
				  'notification_title' => 'SteelMint | Intel',
				  'description' => 'Ex-Mines Orissa India, falls down $100',
				  'category' => 'intel',
				  'category_id' => '',
				  'sent_at' => '2019-09-05 16:11:01',
				  'type' => 'T',
				  'sent_to_groups' => 'auto',
				  'f_url' => '12507',
				  'share_url' => 'https://www.steelmint.com/intel/intel-12507',
				) */
	   return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> $result));
    }
	
	public function showPackageDetails(Request $request)
    {      
		$resourceType = "app";
		$user_id = 0;
		
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$section='';
		if($request->has('section'))
			$section = strtolower($request->input('section'));
		else
			return new JsonResponse(array("status"=>array("code" => 2014, "message" => "section type missing.")));
		
		
		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("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("code" => 2100, "message" => "Unauthorized action."));
		}
		
		//$accessType='pre';//for visitor///
		$activePackegesIDs=array();
		if($user_id){
			$user = new User($user_id, $this->appType);
			$activePackeges = $user->accessiblePackagesToMemid($user_id);	
				
			$activePackegesIDs = $activePackeges['IDs'];
			///print_r($activePackegesIDs);	
		}
		
		$currencyName='';
		if($request->has('currencyName'))
			$currencyName = strtolower($request->input('currencyName'));
		
		$packageID =array();
		if($request->has('packageID'))
			$packageID = $request->input('packageID');
		if($request->has('itemID'))
			$packageID = $request->input('itemID');
		//include_once "/home/steelmin/public_html/api/storage/v2019/package_details.php";
		$result = \ApiQuery::getPackagesRows($user_id, $packageID, $section, 'Active', $resourceType, $activePackegesIDs, $this->appType, $currencyName);
		//, "data"=> $result;
		return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success"), "data"=> $result));
	}
	
		
	public function getloginSuggestedPackage(Request $request){
		$place = strtolower($request->input('place'));
		$result =array(
				
				"suggestedPackage"=>array(
					"packageId" => "2",
					"packageName" => "Standard",
					"whatYouGet" => array("Prices", "Tenders", "Newsletters"),
					"period" => array(
								array(
									"name" => "1 year",
									"isDisabled" => "Y",
									"amountPerMonth" => 4999.0,
									"billed_text" => "Billed Anually",
									"currencyConvertor"=> array(
										"USD"=>array(
											"symbol" => "$",
											"code" => 'USD',
											"amount" => 110.00
										),
										"INR"=>array(
											"symbol" => "₹",
											"code" => 'INR',
											"amount" => 6999.00
										)
									)
								)
					),
					"isActivePackage" => "Y",
					"minimumMagazineYear" => "2019"
				)
			);
		$code = 1001;
		$message = "success";	
		return new JsonResponse(array("status"=>array("code" => $code , "message" => $message), "data"=> $result));
	}
	
	public function getLoginDetails(Request $request)
    {
		$result = array();	
		$resourceType = "app";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($resourceType=='web'){
			$remeberme = strtolower($request->input('remeberme'));
			$password = $request->input('password');
			$email = $request->input('email');
			$remember = $request->has('remember')?$request->input('remember'):'';
			
			$auth = new authentication();
			
			if($request->has('OTP') && $request->input('OTP')!='') {
				$userName = $request->input('userName');
				//$userName = $request->input('userName');
				$refreshToken = $auth->generateRefreshTokenV2019ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id='web', $resourceType, $this->appType);
			}else{
				$password = $request->input('password');
				$userName = $request->input('userName');
				if(empty($userName))
					$userName = $request->input('email');
				/* if ($request->has('DEBUG')){
			
					ECHO $refreshToken = $auth->generateRefreshTokenV2019V1($resourceType, $userName, $password, $request->all(), $remember);
					PRINT_R($_COOKIE);
				}ELSE */
					$refreshToken = $auth->generateRefreshTokenV2019($resourceType, $userName, $password, $request->all(), $remember);
			}
			
			if($refreshToken==false && $request->has('OTP')){
					$code = 2002;
					$message = "Unauthorized action. please enter correct OTP";
					return new JsonResponse(array("status"=>array("code" => $code , "message" => $message)));
			}
			elseif($refreshToken==false){
				$code = 2001;
				$message = "Unauthorized action. please enter correct username and password";
				return new JsonResponse(array("status"=>array("code" => $code , "message" => $message)));
			}
			if ($refreshToken == "NV" )
			{
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action. Email/User not verified"))) ;
//             	abort(403, array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified"));
				
			}elseif ($refreshToken == 'falseIPBL' )
			{
				return new JsonResponse(array("status"=>array("code" => 2100, "message" => "You are not authrised to access out side office"))) ;
				
			}
			/* elseif ($refreshToken == 'falseAccess' )
			{
				return new JsonResponse(array("status"=>array("code" => 2013, "message" => "User already loggedIn from some other device"))) ;
				
			}elseif ($refreshToken == 'trueAL' )
			{
				return new JsonResponse(array("status"=>array("code" => 2013, "message" => "You are already loggedIn"))) ;
				
			} */elseif($refreshToken){
				$code = 1001;
				$message = "success";
				return new JsonResponse(array("status"=>array("code" => $code , "message" => $message), "data"=> $refreshToken));
			}
			
		}else{
			if ((($request->has('userName') || $request->has('email')) && ($request->input('userName')!='' || $request->input('email')!='')) || $request->has('accessToken')) {
				$physical_id = $request->input('deviceID');
				$fcm_token = $request->input('fcmToken');
								
				$auth = new authentication();
				if($request->has('accessToken')) {
					$refreshToken = $request->input('accessToken');
				}elseif($request->has('OTP') && $request->input('OTP')!='') {
					$userName = $request->input('userName');
					//$userName = $request->input('userName');
					$refreshToken = $auth->generateRefreshTokenV2019ByOTP($resourceType, $userName, $request->input('OTP'), $request->input('isdCode'), $physical_id, $request->all(), $remember=0, $this->appType);
				}else{					
					$password = $request->input('password');
					$userName = $request->input('userName');
					if(empty($userName))
						$userName = $request->input('email');
					$refreshToken = $auth->generateRefreshTokenV2019($resourceType, $userName, $password, $request->all(), $remember=0, $this->appType);
				}
				
				if($refreshToken==false && $request->has('OTP')){
					$code = 2002;
					$message = "Unauthorized action. please enter correct OTP";
					return new JsonResponse(array("status"=>array("code" => $code , "message" => $message)));
				}
				elseif($refreshToken==false){
					$code = 2013;
					$message = "Unauthorized action. please enter correct username and password";
					return new JsonResponse(array("status"=>array("code" => $code , "message" => $message)));
				}
				$show_manage_pref_screen='no';
				$user_id = $auth->authRefreshToken($refreshToken) ;
				
				if($request->has('token') && empty($user_id)) {	
					return new JsonResponse(array("status"=>array("code" => 2013, "message" => 'Invalid Refresh Token')));
				}
				
				//include_once "/home/steelmin/public_html/api/storage/v2019/login_details.php";
				$code = 1001;
				$message = "success";
				
				$urlog = DB::table('tbl_reg_logs')
												->select('id')
												->where('memid', '=', $user_id ) 
												->where('status', '=', 'Active' )
												->whereIn('f_product', array('W','MA') )
												->get();

				if (count($urlog) >= 1 ) {
					$_val = 10;
				}else
					$_val = 15;
				
				$result = DB::table($_ENV['USER_TABLE'])
					->select('*')
					->where($_ENV['USER_ID'], '=', $user_id )
					->first();
					
				if($result['is_first_time_user']){
					$show_manage_pref_screen='yes';
					
					DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->where('is_first_time_user', '=', 0 )
					->update( [ 'activity_meter' => $result['activity_meter'] + $_val ]);
				}else{
					DB::table($_ENV['USER_TABLE'])
					->where($_ENV['USER_ID'], '=', $user_id )
					->update( [ 'activity_meter' => $result['activity_meter'] + $_val ]);
				}
				
				if ($refreshToken == "NV" )
				{
					return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action. Email not verified"))) ;
	//             	abort(403, array( "status#" => "1003" , "message#" => "Unauthorized action. Email not verified"));
					
				}
				elseif ($refreshToken == 'MLR' )
				{
					return new JsonResponse(array("status"=>array("code" => 2100, "message" => "You are already loggedIn from some other device"))) ;
					
				}elseif($refreshToken){
					$userType = 'Upgrade';
					//if any active log then its paid
					if ($_val==10)
						$userType = 'Renew';
					
					$user = new User($user_id);
					
					$user_data = $user->get($user_id)  ;
					$result = $user_data;
					//$dataArr= array ("refreshToken" => $refreshToken);
					$result["refreshToken"]=$refreshToken;
					
					$auth = new authentication();
					$token = $auth->generateToken( $refreshToken );
					if ($token) {
						$result["accessToken"]=$token;
						//$result["accessToken"]=$token;
					}
					else {
						$result["accessToken"]="Unauthorized action. Token access denied";
					}
					
					$maxCount =	$user->getTakenServicesByUser();
					if($maxCount == -1)
						$user_type='Paid';
					elseif($maxCount == 0)
						$user_type='Upgrade';
					else
						$user_type='Login';
					
					//add as prem want seprate param for $user_type as $CM_user_type
					$CM_user_type='';
					//if($appType=='CM'){
						$user1 = new User($user_id, 'CM');
						$maxCount_CM =	$user1->getTakenServicesByUser();
						if($maxCount_CM == -1)
							$CM_user_type='Paid';
						elseif($maxCount_CM == 0)
							$CM_user_type='Upgrade';
						else
							$CM_user_type='Login';
					//}
					
					DB::table("gcm_device")
						->where("device_id", '=', $fcm_token )
						->update( [ 'user_id' => $user_id ]);				

					$userSysDtls = $fcm_token . '|' . $refreshToken;
					$loggin_try['mem_id'] = $user_id ;
					$loggin_try['log_time'] = $GLOBALS['currDateTime']; 
					$loggin_try['log_date'] = date("Y-m-d"); 
					$loggin_try['ip_address'] = $_SERVER['REMOTE_ADDR']; 
					
					$loggin_try['device'] = $userSysDtls;
					//$loggin_try['device_name'] = $device_type;
					
					if($physical_id!=''){
						$loggin_try['company'] = ($appType == 'CM')?'CoalMint':'SteelMint';
						$loggin_try['device_id'] = $physical_id;
						$loggin_try['device_name'] = 'android';
					}else{
						$loggin_try['device_name'] = 'IOS';
						//$loggin_try['deviceID'] = $fcm_token;
						if($request->has('appType') && strtoupper($request->input('appType')) == 'CM'){
							$loggin_try['company'] = 'CoalMint';
						}else
							$loggin_try['company'] = 'SteelMint';
					}

					include_once ('/home/steelmin/public_html/hf.php');
					$loggin_try['ip_country'] = ipTocntry($_SERVER['REMOTE_ADDR']);
					
					
					$creden = DB::table('tb1_online_member_loggin_try')
										->select(array('id'))
										->where('mem_id', '=', $user_id )
										->whereIn('device_name', array('android','IOS') )
										->where('company', '=', $loggin_try['company'] )
										->get();
					
					if(!empty($creden)){
						$online_member_loggin_iid = (isset($creden['id']))?$creden['id']:0;
						$loggin_try['parent_loggedin_id'] = $online_member_loggin_iid; 
					}
					
					$loggin_try['platform'] = "Mobile APP";
					$loggin_try['url'] = "public/user/refresh_token : refreshToken - method";
					//print_r($loggin_try);
					///DB::enableQueryLog(); 

					DB::table('tb1_online_member_loggin_try')->insert($loggin_try);
							
					///dd(DB::getQueryLog());		
					if($online_member_loggin_iid==0){
						$last_id = DB::getPdo()->lastInsertId();;
						DB::table('tb1_online_member_loggin_try')
							->where('id', '=', $last_id )
							->update( [ 'parent_loggedin_id' => $last_id]);
						//echo 'get id:'.dd($last_id);
					}	//echo '10';	
					////}
					///end
					calculate_coc($user_id);
					$code = 1001;
					$message = "success";
					$result["service_type"] = $userType;
					$result["user_type"] = $user_type;
					$result["CM_user_type"] = $CM_user_type;
					$result["show_manage_pref_screen"] = $show_manage_pref_screen;
					$result["QRImage"] = BASEURL. "memidQRCodes/".$user_id.".png";
					return new JsonResponse(array("status"=>array("code" => $code , "message" => $message), "data"=> $result));	
					//return new Response( array( "status#" => "1" , "data#" => $dataArr, "service_type#" => $userType, "user_type#" => $user_type, "CM_user_type#" => $CM_user_type, "show_manage_pref_screen#" => $show_manage_pref_screen), 200);
				}					
			}else{
				$code = 2100;
				$message = "Unauthorized action. please enter username and password";
			}
		}
		return new JsonResponse(array("status"=>array("code" => $code , "message" => $message), "data"=> $result));
	}
	
	//update FCMToken -
	public function updateFCMToken(Request $request)
    {      
	    $result = array();
	    
		/* if ($request->has('deviceId') && $request->input('deviceId')!='') {
			$fcmToken = $request->input('fcmToken');//price/insights/tender	
			
			$code = 1001;
			$message = "Token Successfully updated";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		} */
		
	   if($request->has('deviceType') && $request->has('deviceID'))
		{
			$deviceType = $request->input('deviceType'); 
			$physical_id = $request->input('deviceID'); ///FCM TOKEN =>android_id 
			$accessToken = $request->input('accessToken'); 	///token   
			$deviceID = $request->input('fcmToken'); ///android/IOS id (push notification)
			$deviceInfo = $request->input('deviceInfo'); 
			
			$user_id = '' ;
			if($request->has('accessToken'))
			{
				$token = $request->input('accessToken');
				$auth = new authentication();
				$user_id = $auth->authToken($token);
				if (!$user_id)
					return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action. Token access denied"))) ;
			}
			
			///$deviceInfo = $request->input('deviceInfo'); 
			if( $request->input('deviceType') == 'android' || $request->input('deviceType') == 'ios')
			{
				///$deviceID = $request->input('deviceID') ;
				$deviceID = trim($deviceID ) ;
				
				///$_app_ver="8.0";//7.4 missing 	
				$_app_ver= $request->input('deviceType') == 'ios'?"8.0":"8.0";
				
				if($this->appType == 'CM'){ 
					$_app_ver="1.0";	
				}				
				
				$sel_admob=DB::table('gcm_device')->where("device" , "=" , $request->input('deviceType'))->where("device_id" , "=" , $deviceID )->where("appType" , "=" , $this->appType )->first();

				if($sel_admob)
				{
					////$show_admob=$sel_admob['admob'];
					if($user_id){
						DB::table('gcm_device')
							->where("device" , "=" , $request->input('deviceType') )
							->where("deviceInfo" , "=" , $deviceInfo )
							->where("appType" , "=" , $this->appType )
							->update(["user_id" => 0 ]) ;
						
						$uData = array(
							"updated_at"=>$GLOBALS['currDateTime'],
							"device"=>$deviceType,
							"device_id"=>$deviceID,
							"user_id"=>$user_id,
							"memid_immortal"=>$user_id,
							"deviceInfo"=>$deviceInfo,
							"physical_id"=>$physical_id,
							"status"=>'enable',
							"appType"=>$this->appType
						);
						
						$show_admob='N';
						DB::table('gcm_device')
							->where("user_id" , "=" , $request->input('deviceType') )
							->where("device_id" , "=" , $deviceID )
							->where("appType" , "=" , $this->appType )
							->update($uData) ;
					}
					return new JsonResponse(array("status"=>array("code" => 1001, "message" => "Device already registered"))) ;
					/* return new JsonResponse(array(
						"status#" =>"1",
						"message#" => "Device already registered",
						"latest_app_version_in_play_store" => $_app_ver,
						"allow_copy_news" => "0",
						
					)) ; */
				}
				
				$uData = array(
							"created_at"=>$GLOBALS['currDateTime'],
							"device"=>$deviceType,
							"device_id"=>$deviceID,
							"user_id"=>$user_id,
							"memid_immortal"=>$user_id,
							"deviceInfo"=>$deviceInfo,
							"physical_id"=>$physical_id,
							"status"=>'enable',
							"appType"=>$this->appType
						);
						
				//else insert new device details
				DB::table('gcm_device')
					->insert($uData) ;
				
				//return new JsonResponse(array("code" => 1001, "message" => "success" , "latest_app_version_in_play_store" => $_app_ver, "allow_copy_news" => "0"));
				//return new JsonResponse(array("status"=>array("code" => 1001, "message" => "success" , "latest_app_version_in_play_store" => $_app_ver, "allow_copy_news" => "0")));
				return new JsonResponse(array( "status"=>array("code" => 1001, "message" => "success"), "data"=>array( "latest_app_version_in_play_store" => $_app_ver, "allow_copy_news" => "0")));
				
				$code = 1001;
				$message = "success";
			}
			else{
				//$code = 2100;
				$code = 2001;
				$message = "Device not detected.";
				///return new JsonResponse(array("status"=>array("code" => 2013, "message" => "Device not detected"))) ;
			}
		}else{
			//$code = 2100;
			$code = 2001;
			$message = "Invalid request.";
		}
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }
	///user profile
	public function savePersonalDetails(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);
		}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) {			
			$data = array();
			$user = new User($user_id);
			
			if($request->has('name')) {
				if(!empty($request->input('name'))) {
					$data['name'] = $request->input('name');
				} else {
					//return new JsonResponse(array("status#" => "0" , "message#" => "Name must not be empty!"), 200);
					return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Name must not be empty!")));
				}
			}
			
			if($request->has('email') || $request->has('alternateEmail')) {
				if(!empty($request->input('email'))) {
					$value = $request->input('email');
					if ( $user->checkEntryWithOthers('email' , $value, $user_id)){///is user duplicate entry
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "email already registered with some other user.")));
					}
					
					if ($request->has('alternateEmail') && $user->checkEntryWithOthers('addtnl_email' , $value, $user_id)){///is user duplicate entry
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "alternate email already registered with some other user.")));
					}
					
					if($request->has('alternateEmail')){
					    $alternateEmailvalue = $request->input('alternateEmail');
    					if ($user->checkEntryWithOthers('email' , $alternateEmailvalue, $user_id)){///is user duplicate entry in same reg user
    						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "alternate email, already registered with some other user.")));
    					}
    					
    					if ($user->checkEntryWithOthers('addtnl_email' , $alternateEmailvalue, $user_id)){///is user duplicate entry in same reg user
    						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "alternate email, already registered with some other user.")));
    					}
    					
    					if ($user->checkEntryWithSame('email' , $alternateEmailvalue, $user_id)){///is user duplicate entry in same reg user
    						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "alternate email, already registered with same user.")));
    					}
					}
					
					if($resourceType=='app'){					
						$user_data = $user->get($user_id)  ;
						if($request->has('email') && $user_data['email']==''){//update if first time.
							$data['email'] = $request->input('email');							
						}
						
						if($request->has('alternateEmail') && $user_data['alternateEmail']==''){//update if first time.
							$data['addtnl_email'] = $request->input('email');							
						}
						/*$result = DB::table('tbl_members')
							->select('send_email_to')
							->where('id', '=', $user_id)
							->first();
						
						if(isset($result['send_email_to']) && $result['send_email_to'] == 'R') {
							$data['email'] = $request->input('email');
						} else {
							$data['addtnl_email'] = $request->input('email');
						}*/
					}else{
						if($request->has('email'))
							$data['email'] = $request->input('email');
						if($request->has('addtnl_email'))
							$data['addtnl_email'] = $request->input('alternateEmail');
					}
					
				} else {
					return new JsonResponse(array("status"=>array("code" => 2001, "message" => "email. must not be empty!")));
				}
			} 
			
			 if($request->has('phoneno') || $request->has('alternatePhoneno')) {
				if(!empty($request->input('phoneno'))) {
					$value = $request->input('phoneno');
					if ( $user->checkEntryWithOthers('phoneno' , $value, $user_id) || $user->checkEntryWithOthers('alternate_mob_no' , $value, $user_id)){///is user duplicate entry
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "phoneno already registered with some other id.")));
					}
					
					if($request->has('alternatePhoneno')){
					    $alternatePhonenoValue = $request->input('alternatePhoneno');
    					if ($user->checkEntryWithOthers('phoneno' , $alternatePhonenoValue, $user_id)){///is user duplicate entry in same reg user
    						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "alternate phoneno, already registered with some other user.")));
    					}
    					
    					if ($user->checkEntryWithOthers('alternate_mob_no' , $alternatePhonenoValue, $user_id)){///is user duplicate entry in same reg user
    						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "alternate phoneno, already registered with some other user.")));
    					}
    					
    					if ($user->checkEntryWithSame('phoneno' , $alternatePhonenoValue, $user_id)){///is user duplicate entry in same reg user
    						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "alternate phoneno, already registered with same user.")));
    					}
					}
					
					if($resourceType=='app'){					
						/*$result = DB::table('tbl_members')
							->select('send_sms_to')
							->where('id', '=', $user_id)
							->first();
						
						if(isset($result['send_sms_to']) && $result['send_sms_to'] == 'R') {
							$data['phoneno'] = $request->input('phoneno');
						} else {
							$data['alternate_mob_no'] = $request->input('phoneno');
						}*/
					}else{
						if($request->has('phoneno'))
							$data['phoneno'] = $request->input('phoneno');
						if($request->has('alternate_mob_no'))
							$data['alternate_mob_no'] = $request->input('alternatePhoneno');
					}
					
				} else {
					return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Phone no. must not be empty!")));
				}
			} 
			
			if($request->has('DOB')) {
				if(!empty($request->input('DOB'))) {
					$data['dob'] = $request->input('DOB');
				}
			}
			
			if($request->has('jobTitle')) {
				if(!empty($request->input('jobTitle'))) {
					$data['job_title'] = $request->input('jobTitle');
				}
			}
			
			if($request->has('companyName')) {
				if(!empty($request->input('companyName'))) {
					$data['company'] = $request->input('companyName');
				}
			}
			
			if($request->has('companyType')) {
				if(!empty($request->input('companyType'))) {
					$data['companytype'] = $request->input('companyType');
				}
			}
			
			if($request->has('address')) {
				if(!empty($request->input('address'))) {
					$data['address'] = $request->input('address');
				} else {
					return new JsonResponse(array("status#" => "0" , "message#" => "Address must not be empty!"), 200);
				}
			}
			
			/* if($request->has('city') && !empty($request->input('city'))) {
				$data['city'] = $request->has('city');
			}
			if($request->has('state') && !empty($request->input('state'))) {
				$data['state'] = $request->has('state');
			}
			if($request->has('country') && !empty($request->input('country'))) {
				$data['country'] = $request->has('country');
			} */
				if($request->has('location')) {
					if(!empty($request->input('location'))) {
						$location = htmlentities($request->input('location'), ENT_QUOTES);
						$location = explode(",", $location);
						$data['city'] = 0;
						$data['state'] = 0;
						$data['country'] = 0;
						
						if(isset($location[2])) {
							
							$dbresult1 = DB::table('tbl_country')
								->select('id' )				
								->where('country' , trim($location[2]))
								->orWhere('std_code' ,$isdCode)
								->first();
							
							if (count($dbresult1) > 0 ){
								$data['country'] = $dbresult1['id'] ;
							}
						}

						if(isset($location[1])) {
							$dbresult1 = DB::table('tbl_state_city')
								->select('state_id' )				
								->where('state_name' , trim($location[1]))
								->Where('country_id' , $data['country'])
								->first();
							
							if (count($dbresult1) > 0 ){
								$data['state'] = $dbresult1['state_id'] ;
							}
						}

						if(isset($location[0])) {
							$dbresult1 = DB::table('tbl_state_city')
								->select('city_id' )				
								->where('state_name' , trim($location[1]))
								->Where('city_name' , trim($location[0]))
								->first();
								
							if (count($dbresult1) > 0 ){
								$data['city'] = $dbresult1['city_id'] ;
							}
						}
						
						if($data['country']==0){//country not found
							$data['other_city'] = $request->has('location');
						}

					} else {
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Please select location!")));						
					}
				} 
				
			/* if($request->has('location')) {
				if(!empty($request->input('location'))) {
					$location = explode(",", $request->input('location'));
					$data['city'] = 0;
					$data['state'] = 0;
					$data['country'] = 0;

					if(isset($location[0])) {
						$data['city'] = trim($location[0]);
					}

					if(isset($location[1])) {
						$data['state'] = trim($location[1]);
					}

					if(isset($location[2])) {
						$data['country'] = trim($location[2]);
					}

				} else {
					return new JsonResponse(array("status#" => "1006" , "message#" => "Please select location!"), 200);
				}
			} */

			if($request->has('zipCode')) {
				if(!empty($request->input('zipCode'))) {
					$data['pin_code'] = $request->input('zipCode');
				} else {
					return new JsonResponse(array("status"=>array("code" => 2001, "message" => "zip Code must not be empty!")));
				}
			}
	
			if($request->has('profilePic')) {
				$str= str_replace('\\','',$request->input('profilePic'));
				$str= str_replace(' ','+',$str);
				$str = base64_decode($str);

				file_put_contents("/home/steelmin/public_html/images/clients/" . $user_id . ".png", $str);           
				$data['profile_pic'] = $user_id . ".png";
			}

			/* if($request->has('protype')) {
				$data['protype'] = $request->input('protype');
			} else {
				$data['protype'] = "";
			} */

			
			if($request->has('companyProfile')) {
				$data['company_profile'] = $request->input('companyProfile');
			}


			$isd_code = array();

			if($request->has('isdCode')) {
				//$isd_code = explode(" ", htmlspecialchars($request->input('isdCode'), ENT_QUOTES));
				//$data['isd_code'] = end($isd_code);
				$data['isd_code'] = htmlspecialchars($request->input('isdCode'), ENT_QUOTES);
			}

			if($data) {
				DB::table('tbl_members')
					->where('id', $user_id)
					->update($data);
			}
			
			$code = 1001;
			$message = "Successfully Saved";
		}else{
			$code = 2100;
			$message = "Unauthorized action.";
		}
		
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	   //return new JsonResponse(array("code" => $code, "message" => $message));
    }
	
	public function getPersonalDetails(Request $request)
    {
		$result = array();
		
		/* if ($request->has('accessToken') && $request->input('accessToken')!='') {
			$memid = $request->input('memid');
			include_once "/home/steelmin/public_html/api/storage/v2019/personal_details.php";
			$code = 1001;
			$message = "success";
		}else{
			$code = 2100;
			$message = "Access token is invalid or has expired.";
		} */
		$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);
		}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) {
			if ($resourceType=='web'){
				///same
			}else{//$resourceType=='app'
				//same
			}
			$user = new User($user_id);
			$result = $user->getProfile($user_id)  ;
			if ( $result ){
				$code = 1001;
				$message = "success";
			}else{
				$code = 2013;
				$message = "No user data";
			}
		}else{
			$code = 2001;
			$message = "Unauthorized action";
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}	
	
	//register -
	public function renewPackages(Request $request){
		/*if ($request->has('section'))
			$section = strtolower($request->input('section'));
		else
			return new JsonResponse(array("status"=>array("code" => 2001, "message" => " section is missing")));*/
		
		if(!$request->has('logID')) {//tbl_reg_log.id
			return new JsonResponse(array("status"=>array("code" => 2001, "message" => "invalid logID for renew!")));
		}else{
			$logID = $request->input('logID');
			
			$dbresult = DB::table('tbl_reg_logs')
				->select('*' )				
				->where('id' , $logID)
				->orWhere('parent_id' , $logID)
				->orderBy('parent_id' , 'asc')
				->get();
				
			$paren_logID=0;
			$paren_memid= 0;
			$servType= 'Renew Service';
			if (count($dbresult) > 0){
				foreach($dbresult as $logs){
					$logs['id'] = '';
					$packageID= $logs['selected_products'];
					$memid= $logs['memid'];
					
					//if($logs['parent_id']==0){
						$dbresult2 = DB::table('tbl_packages')
						->select('*' )				
						->where('id' , (int)$packageID)
						->get();
						
						if (count($dbresult2) > 0){
							$packageName =  $dbresult2[0]['packageName'] ;
							$periodName =  $dbresult2[0]['period_name'] ;
							$totalAmountWoGST =  $dbresult2[0]['totalAmount_Wo_GST'] ;
							$totalAmountWithGST =  $dbresult2[0]['totalAmount_With_GST'] ;
							$discountPercentage =  $dbresult2[0]['discount_percentage'] ;
							$amountPerMonth =  $dbresult2[0]['amountPerMonth'] ;
							$currencyCode =  $dbresult2[0]['currency_code'] ;
							/* $scratch_value =  $dbresult2[0]['scratch_value'] ;
							
							$packageGroupID =  $dbresult2[0]['group_id'] ;
							$packageSubGroupId =  $dbresult2[0]['sub_group_id'] ;
							$packageOrder =  $dbresult2[0]['package_order'] ; */
						}
					//}
					//copy row with following changes
					$logs['startdate']= date("Y-m-d",strtotime($logs['enddate']." +1 day"));	
					$logs['enddate']= date("Y-m-d",strtotime($logs['startdate']." +$periodName months"));
					$logs['f_time']= $GLOBALS['currTime'];
					$logs['status']= 'Pending';
					$logs['comments']= 'Renew Service';
					$logs['amtPaid']= $totalAmountWithGST;
					$logs['amountWOTax']= $totalAmountWoGST;
					$logs['created_on']= $GLOBALS['currDateTime'];
					$logs['datepay']= "0000-00-00 00:00:00";
					$logs['paymentstatus']= "Pending";
					$logs['pipeline_status']= "New";
					$logs['mapping_id']= "";				
					$logs['parent_id']= $paren_logID;				
					
					try{
						$_log_id = DB::table('tbl_reg_logs')->insertGetId($logs);	
					} catch (QueryException $e) {
						dd($e);
					}
				
					if(!empty($_log_id) && $rm_arr['first_log_id']=='')
					{
						//$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
						//update_table_from_array_of_array($_newUpdtArr,$_log_id);		
							$data['first_log_id'] = $_log_id;
							DB::table('tbl_reg_logs')
								->where('id', $_log_id)
								->update($data);				
					}
				
					if($logs['parent_id']==0){
						$paren_logID = $_log_id;
						$paren_memid= $memid;
					}
				}
				
				DB::table($_ENV['COMMENTS_TABLE'])->insert([ 'memid' => $paren_memid,
							'f_date' => $GLOBALS['currDate'],
							'f_time' => $GLOBALS['currTime'],
							'comments' => "Request Service Type : ".$servType,
							'created_by' => 'self',
							'comments_for' => '']);	

				///
				$userMessage='';
				/* if($packageName=='Price Only'){//send mail to RM and Show RM contact deatils to user
					$userMessage =  \ApiQuery::sendRequestMailToRM($paren_memid);
					$paymentURL='';
					$paymentType='';
				}else */{
					$paymentURL='https://www.theitbooth.com/pay/newCheckOut_new.php';
					$paymentType='sdk';
				}
				$result = array(
					"paymentType"=>$paymentType,
					"paymentURL"=>$paymentURL,
					"message"=>$userMessage,//if no payment neended
					"packageName"=>$packageName,
					"lastLogId"=>$paren_logID,
					"totalAmount"=>$totalAmountWoGST,
					"amountPayable"=>$totalAmountWithGST,
					///"tax"=>900,
					"discount"=>round(($totalAmountWoGST*$discountPercentage)/100, 2),
					"discountPercentage"=>$discountPercentage,
					"currency"=>$currencyCode				
				);
				$code = 1001;
				$message = "Successfully Register";
			}
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
		}
	}
	
	public function register(Request $request)
    {      
	    $result = array();
	   
		$resourceType = "app";
		$section = "steelmint";
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if ($request->has('section'))
			$section = strtolower($request->input('section'));
		
		if($section=="steelmint" && $resourceType=='web'){
			$f_product = 'W';
		}
		if($section=="steelmint" && $resourceType=='app'){
			$f_product = 'MA';
		}
		
		$licensesCount=1;
		if(!$request->has('packageID')) {
			return new JsonResponse(array("status"=>array("code" => 2001, "message" => "invalid package selection!")));
		}else{
			$packageID = $request->input('packageID');
		}
		
		if($request->has('email') && $request->has('mobileNo')) {
			if(empty($request->input('email'))) {
				return new JsonResponse(array("status"=>array("code" => 2001, "message" => "mobile no not be empty!")));
			}
			if(empty($request->input('mobileNo'))) {
				return new JsonResponse(array("status"=>array("code" => 2001, "message" => " mobile no not be empty!")));
			}
			
			
			$email = $request->input('email');
			$mobileNo = $request->input('mobileNo');
			$isdCode = $request->input('isdCode');
			
			if($request->has('licensesCount'))
				$licensesCount = $request->input('licensesCount');

			/* if ( $user->checkEntryWithOthers('email' , $value, $user_id) || $user->checkEntryWithOthers('alternateEmail' , $value, $user_id)){///is user duplicate entry
				return new JsonResponse(array("status"=>array("code" => 2001, "message" => "email already registered with some other id.")));
			} */
				
			$ipAddress = $_SERVER['REMOTE_ADDR'];	
			//DB::enableQueryLog(); 
			$dbresult = DB::table($_ENV['USER_TABLE'])
					->select('id')
					->where(function($q) use ($email) {
								$q->where('email' ,$email)
								->orWhere('addtnl_email' ,$email)
								->orWhere('username' ,$email);
							})
					->orWhere(function($q) use ($mobileNo) {
								$q->where('phoneno' ,$mobileNo)
								->orWhere('alternate_mob_no' ,$mobileNo)
								->orWhere('username' ,$mobileNo);
							})
					->first();
			//dd(DB::getQueryLog());
			$location='';
			$comments=$section.'<br>';
			
			if (count($dbresult) == 0 ){///new user 
				
				$newUser['email'] = $email;
				$newUser['username'] = $email;
				$newUser['phoneno'] = $mobileNo;
				$newUser['isd_code'] = $isdCode;
				
					if($request->has('name')) {
						if(!empty($request->input('name'))) {
							$newUser['name'] = htmlentities($request->input('name'), ENT_QUOTES);
						} else {
							//return new JsonResponse(array("status#" => "0" , "message#" => "Name must not be empty!"), 200);
							return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Name must not be empty!")));
						}
					}
					if($request->has('jobTitle')) {
						if(!empty($request->input('jobTitle'))) {
							$newUser['job_title'] = htmlentities($request->input('jobTitle'), ENT_QUOTES);;
						}else {
							return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Job Title must not be empty!")));
						}
					}
				
					if($request->has('companyName')) {
						if(!empty($request->input('companyName'))) {
							$newUser['company'] = htmlentities($request->input('companyName'), ENT_QUOTES);;
						}else {
							return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Company Name must not be empty!")));
						}
					}
					
					if($request->has('companyType')) {
						if(!empty($request->input('companyType'))) {
							$newUser['companytype'] = $request->input('companyType');
						}else {
							return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Select company type!")));
						}
					}
					
				if($request->has('location')) {
					if(!empty($request->input('location'))) {
						$location = htmlentities($request->input('location'), ENT_QUOTES);
						$location = explode(",", $location);
						$newUser['city'] = 0;
						$newUser['state'] = 0;
						$newUser['country'] = 0;
						
						if(isset($location[2])) {
							
							$dbresult1 = DB::table('tbl_country')
								->select('id' )				
								->where('country' , trim($location[2]))
								->orWhere('std_code' ,$isdCode)
								->first();
							
							if (count($dbresult1) > 0 ){
								$newUser['country'] = $dbresult1['id'] ;
							}
						}

						if(isset($location[1])) {
							$dbresult1 = DB::table('tbl_state_city')
								->select('state_id' )				
								->where('state_name' , trim($location[1]))
								->Where('country_id' , $newUser['country'])
								->first();
							
							if (count($dbresult1) > 0 ){
								$newUser['state'] = $dbresult1['state_id'] ;
							}
						}

						if(isset($location[0])) {
							$dbresult1 = DB::table('tbl_state_city')
								->select('city_id' )				
								->where('state_name' , trim($location[1]))
								->Where('city_name' , trim($location[0]))
								->first();
								
							if (count($dbresult1) > 0 ){
								$newUser['city'] = $dbresult1['city_id'] ;
							}
						}

					} else {
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Please select location!")));						
					}
				} 
				
				if($request->has('address')) {
					if(!empty($request->input('address'))) {
						$newUser['address'] = $request->input('address');
					} else {
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Address must not be empty!")));						
					}
				}
				$password='123456';
				if($request->has('password')) {
					if(!empty($request->input('password'))) {
						$password = $request->input('password');
					}elseif(strlen($request->input('password'))<6){
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "password must be greater then 5 characters!")));
					} else {
						return new JsonResponse(array("status"=>array("code" => 2001, "message" => "password must not be empty!")));
					}
				}
				
				$type='new';
				
				$newUser['password'] = $password;
				$newUser['ol_be'] = 'MOB APP OTP';
				$newUser['main_source'] = $section.' APP';
				$newUser['source_from'] = 'New APP';
				$newUser['ipaddress'] = $ipAddress;
				$newUser['date'] = $GLOBALS['currDateTime'];
				$newUser['primary_source'] = 'CAMP19';
				$newUser['lead_type'] = 'A1';
				
				if($request->has('promotionalMails') && !empty($request->input('promotionalMails'))) {
					$newUser['email_category'] = '22';
				}
				
				$memid = DB::table('tbl_members')->insertGetId($newUser);			
				
			}else{//existing user
				$memid = $dbresult['id'] ;
				$type='old';
				
				
				foreach($request->all() as $key=>$subvalue)
				{	
					$comments = $comments." $key => ".$subvalue." <br /> ";
				}
				
				$comments .= "<br> Tried to register in ".$resourceType." <br /> ";
				$comments .= " ip => ".$ipAddress." <br /> ";
			}
			$more_memids='';$chiledIds=array();
			if($request->has('moreLicenses')){
				
				$licensesCount = $request->input('licensesCount');
				foreach($request->input('moreLicenses') as $license){
					$email =  htmlentities($license['email'], ENT_QUOTES);
					if(!empty(trim($email))){
						$name = htmlentities($license['name'], ENT_QUOTES);
						$mobileNo = htmlentities($license['mobileNo'], ENT_QUOTES);
						//
						$dbresult0 = DB::table($_ENV['USER_TABLE'])
							->select('id')
							->where(function($q) use ($email) {
										$q->where('email' ,$email)
										->orWhere('addtnl_email' ,$email)
										->orWhere('username' ,$email);
									})
							->orWhere(function($q) use ($mobileNo) {
										$q->where('phoneno' ,$mobileNo)
										->orWhere('alternate_mob_no' ,$mobileNo)
										->orWhere('username' ,$mobileNo);
									})
							->first();
						//dd(DB::getQueryLog());
						
						if (count($dbresult0) == 0 ){///invalid or new user 
							//$code = 2100;
							//$message = "invalid user.";
							$_type='new';
							$newUser['username'] = $email;
							$newUser['email'] = $email;
							$newUser['phoneno'] = $mobileNo;
							$newUser['isd_code'] = $isdCode;
							$newUser['password'] = '123456';
							$newUser['ol_be'] = 'MOB APP OTP';
							$newUser['main_source'] = 'SteelMint APP';
							$newUser['source_from'] = 'New APP';
							$newUser['ipaddress'] = $ipAddress;
							$newUser['date'] = $GLOBALS['currDateTime'];
							$newUser['primary_source'] = 'CAMP19';
							$newUser['lead_type'] = 'A1';
							$newUser['parentMemID'] = $memid;
							
							$new_memid = DB::table('tbl_members')->insertGetId($newUser);
							if($more_memids)
								$more_memids.=",";
							$more_memids.=$new_memid;
							
						}else{
							$new_memid = $dbresult0['id'] ;
							$_type='old';	
							if($more_memids)
								$more_memids.=",";
							$more_memids.=$new_memid;
							
							
						}
						
						$chiledIds[$new_memid] = $_type;
					}
				}
				$comments .= " Register For => ".$more_memids." <br /> ";
				
				
			}
			///print_r($chiledIds);
			DB::table($_ENV['COMMENTS_TABLE'])->insert([ 'memid' => $memid,
						'f_date' => $GLOBALS['currDate'],
						'f_time' => $GLOBALS['currTime'],
						'comments' => $comments. "<br><br>Google Location : ".$location,
						'created_by' => 'self',
						'comments_for' => $resourceType]);	
			
			DB::table('tbl_campaign_history')->insert([ 'memid' => $memid,
						'created_on' => $GLOBALS['currDateTime'],
						'refral_url' => '',
						'camp_code' => 'CAMP19',
						'ip' => $ipAddress,
						'source' => $resourceType]);	
						
					
			$dbresult2 = DB::table('tbl_packages')
				->select('*' )				
				->where('id' , $packageID)
				->get();
				
			if (count($dbresult2) > 0 ){
				$tabType =  $dbresult2[0]['tabType'] ;
				$packageName =  $dbresult2[0]['packageName'] ;
				$periodName =  $dbresult2[0]['period_name'] ;
				$totalAmountWoGST =  $dbresult2[0]['totalAmount_Wo_GST'] ;
				$totalAmountWithGST =  $dbresult2[0]['totalAmount_With_GST'] ;
				$discountPercentage =  $dbresult2[0]['discount_percentage'] ;
				$gst_Rate =  $dbresult2[0]['gst_Rate'] ;
				$gst_Amt =  $dbresult2[0]['gst_Amt'] ;
				$billed_text =  $dbresult2[0]['billed_text'] ;
				$amountPerMonth =  $dbresult2[0]['amountPerMonth'] ;
				$scratch_value =  $dbresult2[0]['scratch_value'] ;
				$currencyCode =  $dbresult2[0]['currency_code'] ;
				
				$packageGroupID =  $dbresult2[0]['group_id'] ;
				$packageSubGroupId =  $dbresult2[0]['sub_group_id'] ;
				$packageOrder =  $dbresult2[0]['package_order'] ;
			}else{			
				$tabType = $request->input('tabType');
				$currencyCode = $request->input('currencyCode');
				$packageName = $request->input('packageName');
				$periodName = $request->input('periodName');//12 months
				$totalAmountWoGST = $request->input('totalAmountWoGST');//12 months
				$totalAmountWithGST = $request->input('totalAmountWithGST');//12 months
				$discountPercentage = $request->input('discountPercentage');//12 months
				$amountPerMonth = $request->input('amountPerMonth');//12 months
				$scratchValue = $request->input('scratchValue');//12 months
				
				$gst_Rate = $request->input('gstRate');//12 months
				$gst_Amt = $request->input('gstAmt');//12 months
				$billed_text = $request->input('billedtext');//12 months
				
			//$licensesCount
			}
			
			
			require_once("/home/steelmin/public_html/hf.php");
			
			$arr=array();
    
			$lead_type='A1';$mood='';$fudate='';
			if($type=='old'){
				//$lead_type = getLastLeadType($memid, $service_type=$f_product);
				$leadtypeArr = getLastLeadType($memid, $service_type=$f_product,$dflag='true');
				if(isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type']!='')
					$lead_type = $leadtypeArr['lead_type'];
				if(isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type']!='')
					$mood = $leadtypeArr['mood'];
				if(isset($leadtypeArr['fudate']) && $leadtypeArr['fudate']!='')
					$fudate = $leadtypeArr['fudate']; 
				
				if($lead_type=='A5' || $lead_type=='B5')
					$lead_type='A11';
			}
			
			$rm_arr =getRMForRoutingProcess($memid, $company_name=strtolower($section), $lead_type);
			//print_R($rm_arr);
			/* $start_date= $GLOBALS['currDate'];
			$end_date=date("Y-m-d",strtotime("$start_date +$periodName months")); */
			
			$f_tenure = strtolower($section)=="steelmint"?'One Year':$periodName.' months';
			//$price = $dtls[23] * $_tax;
			
			$activePackages = DB::table('tbl_reg_logs')
							->select('selected_products as packageID', 'tbl_reg_logs.enddate', 'tbl_packages.group_id', 'tbl_packages.sub_group_id', 'tbl_packages.package_order')
							->leftJoin('tbl_packages', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
							->where('tbl_reg_logs.memid' , '=' , $memid)
							->where('tbl_reg_logs.status' , '=' , 'Active')
							->orderBy('selected_products' , 'desc')
							->first();
			if (count($activePackages) > 0 ){
				$activePackageID = (int)$activePackages['packageID'];
				$activePackageGroupId = (int)$activePackages['group_id'];
				$activePackageSubGroupId = (int)$activePackages['sub_group_id'];
				$activePackageOrder = (int)$activePackages['package_order'];
				
				if($packageGroupID < $activePackageGroupId)
					$servType = 'Downgrade';
				elseif($packageGroupID == $activePackageGroupId){
					if($packageSubGroupId < $activePackageSubGroupId)
						$servType = 'Downgrade';
					elseif($packageOrder < $activePackageOrder)
						$servType = 'Downgrade';
					else
						$servType = 'Renew';
				}else
					$servType = 'Upgrade';				
			}
			
			$start_date= $GLOBALS['currDate'];	
			if($servType=='Downgrade' || $servType=='Renew'){
				//$start_date= $activePackages['enddate'];				
				$start_date= date("Y-m-d",strtotime($activePackages['enddate']." +1 day"));			
			}elseif($servType=='Upgrade'){//currDate when to inactive current log
				$start_date= $GLOBALS['currDate'];				
			}
			
			$end_date=date("Y-m-d",strtotime("$start_date +$periodName months"));

			$tbl_reg_logs=array(
				'memid'=>$memid,
				'startdate'=>$start_date,
				'enddate'=>$end_date,
				'f_time'=>$GLOBALS['currTime'],
				'f_product'=>$f_product,
				'f_tenure'=>$f_tenure,//'One Year',
				'status'=>'Pending',
				'selected_products'=>$packageID,
				'comments'=>$resourceType,
				'amtPaid'=>$totalAmountWithGST,
				'amountWOTax'=>$totalAmountWoGST,
				'created_on'=>$GLOBALS['currDateTime'],
				'lead_type'=>$lead_type,
				'fudate'=>$fudate,
				'rm'=>$rm_arr['rm_id'],
				'subrm'=>$rm_arr['subrm_id'],
				'mood'=>$mood,
				'pipeline_status'=>'New',
				'routing_status'=>$lead_type,
				'first_log_id' => $rm_arr['first_log_id']
			);
			//print_r($tbl_reg_logs);
			
			/* $r = create_logs_from_array_of_array($arr);
			$_log_id = $r['tbl_reg_logs']; */
			try{
				$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);	
			} catch (QueryException $e) {
				dd($e);
			}

            if(!empty($_log_id) && $rm_arr['first_log_id']=='')
			{
				//$_newUpdtArr['tbl_reg_logs']['first_log_id']=$_log_id;
				//update_table_from_array_of_array($_newUpdtArr,$_log_id);		
					$data['first_log_id'] = $_log_id;
					DB::table('tbl_reg_logs')
						->where('id', $_log_id)
						->update($data);				
			}
			//start packeges for child rows
			foreach($chiledIds as $cMemid=>$_type){
				$lead_type='A1';$mood='';$fudate='';
				if($_type=='old'){
					//$lead_type = getLastLeadType($memid, $service_type=$f_product);
					$leadtypeArr = getLastLeadType($cMemid, $service_type=$f_product,$dflag='true');
					if(isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type']!='')
						$lead_type = $leadtypeArr['lead_type'];
					if(isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type']!='')
						$mood = $leadtypeArr['mood'];
					if(isset($leadtypeArr['fudate']) && $leadtypeArr['fudate']!='')
						$fudate = $leadtypeArr['fudate']; 
					
					if($lead_type=='A5' || $lead_type=='B5')
						$lead_type='A11';
				}
				
				$rm_arr =getRMForRoutingProcess($cMemid, $company_name=strtolower($section), $lead_type); 
				
				$tbl_reg_logs=array(
					'memid'=>$cMemid,
					'parent_id'=>$_log_id,
					'startdate'=>$start_date,
					'enddate'=>$end_date,
					'f_time'=>$GLOBALS['currTime'],
					'f_product'=>$f_product,
					'f_tenure'=>$f_tenure,
					'status'=>'Pending',
					'selected_products'=>$packageID,
					'comments'=>$resourceType,
					'amtPaid'=>$totalAmountWithGST,
					'amountWOTax'=>$totalAmountWoGST,
					'created_on'=>$GLOBALS['currDateTime'],
					'lead_type'=>$lead_type,
					'fudate'=>$fudate,
					'rm'=>$rm_arr['rm_id'],
					'subrm'=>$rm_arr['subrm_id'],
					'mood'=>$mood,
					'pipeline_status'=>'New',
					'routing_status'=>$lead_type,
					'first_log_id' => $rm_arr['first_log_id']
				);
				//$r = create_logs_from_array_of_array($arr);
				//$_log_id = $r['tbl_reg_logs'];
				$c_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);	
				if(!empty($c_log_id) && $rm_arr['first_log_id']=='')
				{
					//$_newUpdtArr['tbl_reg_logs']['first_log_id']=$c_log_id;
					//update_table_from_array_of_array($_newUpdtArr,$_log_id);		
						$data['first_log_id'] = $c_log_id;
						DB::table('tbl_reg_logs')
							->where('id', $c_log_id)
							->update($data);				
				}
			}///end
			
			DB::table($_ENV['COMMENTS_TABLE'])->insert([ 'memid' => $memid,
						'f_date' => $GLOBALS['currDate'],
						'f_time' => $GLOBALS['currTime'],
						'comments' => "Request Service Type : ".$servType,
						'created_by' => 'self',
						'comments_for' => $resourceType]);	
			
			
		}else {
			return new JsonResponse(array("status"=>array("code" => 2001, "message" => "please give Email and Mobile no!")));
		} 		
		
		$userMessage='';
		//if($packageName=='Price Only'){//send mail to RM and Show RM contact deatils to user
		if($tabType=='productWise'){//send mail to RM and Show RM contact deatils to user
			$userMessage =  \ApiQuery::sendRequestMailToRM($memid);
			$paymentURL='';
			$paymentType='';
		}else{
			//$paymentURL='https://www.theitbooth.com/pay/newCheckOut_new.php';
			//$paymentType='sdk';
			$paymentType='web';
			$paymentURL='https://www.steelmint.com/pay/newCheckOut_new.php?reglogs_id='.$_log_id.'&uid='.$memid.'&pymtSrc=website&productPurchased='.$packageName.'&amt='.$totalAmountWithGST.'&pckg_incl_sms=0';
		}
			
		if($resourceType=='web'){
			
			$result = array(
				"paymentType"=>"web",//sdk/web
				"paymentURL"=>$paymentURL,//"https://www.theitbooth.com/pay/newCheckOut_new.php",
				"message"=>$userMessage,//if no payment neended
				"packageName"=>$packageName,				
				"lastLogId"=>$_log_id,
				"totalAmount"=>$totalAmountWoGST,
				"amountPayable"=>$totalAmountWithGST,
				"gstAmt"=>$gst_Amt,
				"gstRate"=>$gst_Rate,
				"billedText"=>$billed_text,
				///"tax"=>900,
				"discount"=>round(($totalAmountWoGST*$discountPercentage)/100, 2),
				"discountPercentage"=>$discountPercentage,
				"currency"=>$currencyCode			
			);
			$code = 1001;
			$message = "Successfully Registered";
		}else{
			$deviceId = $request->input('deviceID');
			if ($request->has('deviceID') && $request->input('deviceID')!='') {
				$fcmToken = $request->input('fcmToken');
				$userDetails = $request->input('userDetails');
				$packageDetails = $request->input('packageDetails');
				
				$result = array(
					"paymentType"=>$paymentType,
					"paymentURL"=>$paymentURL,
					"message"=>$userMessage,//if no payment neended
					"packageName"=>$packageName,
					"lastLogId"=>$_log_id,
					"totalAmount"=>$totalAmountWoGST,
					"amountPayable"=>$totalAmountWithGST,
					"gstAmt"=>$gst_Amt,
					"gstRate"=>$gst_Rate,
					"billedText"=>$billed_text,
					///"tax"=>900,
					"discount"=>round(($totalAmountWoGST*$discountPercentage)/100, 2),
					"discountPercentage"=>$discountPercentage,
					"currency"=>$currencyCode				
				);
				$code = 1001;
				$message = "Successfully Registered";
			}else{
				$code = 2100;
				$message = "Access token is invalid or has expired.";
			}
		}
		
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
    }
	
	public function sendOTP(Request $request)
    {      
	    $resourceType = "app";			
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		$result = array();
	    $mobileNumber = $request->input('mobileNumber');
	    $deviceID='web';
		if($request->has('deviceID') && $request->has('deviceID')!='')
			$deviceID = $request->input('deviceID');
		$OTP ='';$isdCode='';
		if ($request->has('mobileNumber') && $request->input('mobileNumber')!='') {
			$isdCode = urlencode($request->input('isdCode'));//price/insights/tender	
			if($request->has('countryCode'))
				$isdCode = urlencode($request->input('countryCode'));
			$mobileNumber = $request->input('mobileNumber');//price/insights/tender	
			$ipAddress = $_SERVER['REMOTE_ADDR'];	
			//DB::enableQueryLog(); 
			$dbresult = DB::table($_ENV['USER_TABLE'])
				->select('id')
				->where(function($q) use ($mobileNumber) {
							$q->where('email' ,$mobileNumber)
							->orWhere('addtnl_email' ,$mobileNumber)
							->orWhere('phoneno' ,$mobileNumber)
							->orWhere('alternate_mob_no' ,$mobileNumber)
							->orWhere('username' ,$mobileNumber);
						})
				->get();
			//dd(DB::getQueryLog());
			if (count($dbresult) == 0 ){///invalid or new user 
				//$code = 2100;
				//$message = "invalid user.";
				$type='new';
				$newUser['username'] = $mobileNumber;
				$newUser['phoneno'] = $mobileNumber;
				$newUser['isd_code'] = $isdCode;
				$newUser['password'] = '123456';
				$newUser['ol_be'] = 'MOB APP OTP';
				$newUser['main_source'] = 'SteelMint APP';
				$newUser['source_from'] = 'New APP';
				$newUser['ipaddress'] = $ipAddress;
				$newUser['date'] = $GLOBALS['currDateTime'];
				$newUser['primary_source'] = 'CAMP19';
				$newUser['lead_type'] = 'A1';
				
				$memid = DB::table('tbl_members')->insertGetId($newUser);

			}else{
				$memid = $dbresult[0]['id'] ;
				$type='old';				
			}
			
			///echo $type;
			//require_once("/home/steelmin/public_html/inc/config1.php");
			require_once("/home/steelmin/public_html/hf.php");
			
			$phnno = $mobileNumber;
			$dbresult = DB::table('tbl_loggin_by_otp')
				->select('OTP' )				
				->where('emailOrPhone' , $phnno)
				->where('memid' ,$memid)
				->where('deviceID' ,$deviceID)
				->get();
				
			if (count($dbresult) > 0 ){
				$OTP = $dbresult[0]['OTP'] ;
			}else{
				$OTP = rand ( 1000 , 9999 );
				
				
				//DB::enableQueryLog(); 
				DB::table('tbl_loggin_by_otp')->insert([ 'ip' => $ipAddress,
							'memid' => $memid,
							'isdCode' => $isdCode,
							'emailOrPhone' => $phnno,
							'otp' => $OTP,
							'deviceID' => $deviceID,
							'created_on' => $GLOBALS['currDateTime']]);
				//dd(DB::getQueryLog());
			}
			
			$result['userType']=$type;
			//$result['OTP']=(int)$OTP;
			$result['memid']=$memid;
			$msg='OTP is '.$OTP.' for SteelMint login. Valid till next 2 hrs only. Dont share OTP for security reasons';
			
			if($resourceType=='app')
				sendBULKsms($phnno, $msg, '', $senderid = 'MINTTT');
			else{
				require_once("/home/steelmin/public_html/mf.php");
				sendSMMail($msg, $email=$phnno, $name='SteelMint', "SteelMint: OTP Credentials", $attachment="", $from_email='info@steelmint.com', $from_name='info@steelmint.com', $reply_to='info@steelmint.com');
			}
			
			$code = 1001;
			$message = "OTP Sent";		
			
		}else{
			$code = 2100;
			$message = "invalid request.";
		}
		
	   //, "data"=> $result;
	  return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));   
    }
	
	public function verifyOTP(Request $request)
    {      
	    $result = array();
	    $deviceID='web';
		if($request->has('deviceID') && $request->has('deviceID')!='')
			$deviceID = $request->input('deviceID');
		if (($request->has('deviceID') && $request->input('deviceID')!='') || $request->has('resourceType')) {
			//$memid = $request->input('memid');//price/insights/tender	
			    $memid = htmlentities($request->input('memid'), ENT_QUOTES);

                if( !is_numeric($memid) ){
                    return new JsonResponse(array("status"=>array("code" => 2001, "message" => "Improper input values")));
                }
			
			$isdCode = $request->input('isdCode');
			$mobileNumber = $request->input('mobileNumber');
			$OTP = $request->input('OTP');
			
			$result = DB::table('tbl_loggin_by_otp')
				->select('id' )				
				->where('emailOrPhone' ,$mobileNumber)
				->where('otp' ,$OTP)
				->where('deviceID' ,$deviceID)
				//->where('memid' ,$memid)
				->get();
			if (count($result) == 0 ){
				$code = 2002;
				$message = "invalid OTP.";
			}else{
				if($memid) {
					$data['is_mobile_verified'] = 1;
					$data['verified'] = 1;
					DB::table('tbl_members')
						->where('id', $memid)
						->update($data);
				}
				$code = 1001;
				$message = "Successfully verified";
			}			
			
		}else{
			$code = 2002;
			$message = "Access token is invalid or has expired.";
		}
		
	   //, "data"=> $result;
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }
	
	public function forgotPassword(Request $request)
    {      
	    $result = array();
	    //$accessToken = $request->input('accessToken');
		$resourceType = "app";
			
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($request->has('email'))
    	{
    		$user = new User();
			
    		if($user->forgetPassword($request->input('email'), $this->appType))
    		{
				$code = 1001;
				$message = "Password send successfully check your email or SMS";
    			
    		}else{

				$code = 2001;
				$message = "Invalid email or phone!";
			}
			///return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    		
    	}else{
			$code = 2001;
			$message = "Invalid email or phone!";
		}
				
	   //, "data"=> $result;
	   //return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	   return new JsonResponse(array("code" => $code, "message" => $message));
    }
	
	public function resetPassword(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);
		}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) {
			$oldPassword = $request->input('oldPassword');//oldPassword
			$newPassword = $request->input('newPassword');
			
			if($oldPassword=='' && $resourceType=='app') {
				$code = 2001;
				$message = "Invalid old password!";
				return new JsonResponse(array("code" => $code, "message" => $message));
			}

			if($newPassword=='') {
				$code = 2001;
				$message = "Invalid new password!";
				
				return new JsonResponse(array("code" => $code, "message" => $message));
			}
			
			 $result = DB::table('tbl_members')
                    ->select('password')
                    ->where('id', '=', $user_id)
                    ->first();
			
			if($request->has('verifiedThroughOTP') && strtolower($request->input('verifiedThroughOTP'))=='y'){
				//no need to check old password
			}else{
				if(!$result || ($result['password'] != $oldPassword && $oldPassword!='')) {
					return new JsonResponse(array("code" => 2100, "message" => "Old password does not match!"));
				}
			}

			$data['password'] = $newPassword;

			if($data) {
				DB::table('tbl_members')
					->where('id', $user_id)
					->update($data);
			}
			$code = 1001;
			$message = "Password updated successfully";
		}else{
			$code = 2013;
			$message = "Invalid  User";
		}
		
	   //, "data"=> $result;
	   //return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	   return new JsonResponse(array("code" => $code, "message" => $message));
	}

	public function mapGo(Request $request){
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$dataType = strtolower($request->input('dataType'));
		$result = array();	
		if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			if ($request->has('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")));
                }
				
			}else{
				
			}
		}
		//return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
		return new JsonResponse(array("code" => $code, "message" => $message));
	}

	public function mapSave(Request $request){
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));

		$dataType = strtolower($request->input('dataType'));	
		if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			if ($request->has('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")));
                }
				
			}else{
				
			}
		}
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	

	public function mapDownload(){
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$dataType = strtolower($request->input('dataType'));
		if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			if ($request->has('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")));
                }
				
			}else{
			
			}
		}
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));
	}
	
	public function mapSelected(Request $request){
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$dataType = strtolower($request->input('dataType'));
		if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			if ($request->has('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")));
                }
			    
				include_once "/home/steelmin/public_html/api/storage/v2019/web/web_map_sel_post.php";
			}else{
				include_once "/home/steelmin/public_html/api/storage/v2019/web/web_map_sel_post.php";
			}
		}
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));   
	}
	
	public function search(Request $request){
		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		//if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			include_once "/home/steelmin/public_html/api/storage/v2019/web/web_search.php";
		//}
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));   
	}
	
	public function getSubscriptionDetails(Request $request){
		$resourceType = "app";
		$user_id = 0;
		
		$result = array();	
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		$section='';
			
		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');
			    $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///
		$activePackegesIDs=array();
		if($user_id){
			$user = new User($user_id, $this->appType);
			$activePackeges = $user->accessiblePackagesToMemid($user_id);	
				
			//$activePackegesIDs = $activePackeges['IDs'];
			
			$logs = DB::table('tbl_reg_logs')
					->leftJoin('tbl_packages', 'tbl_packages.id', '=', 'tbl_reg_logs.selected_products')
					->select("tbl_packages.*", 'tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status', 'tbl_reg_logs.autoRenewal', 'tbl_reg_logs.inv_no', 'tbl_reg_logs.f_product')
					->where('tbl_reg_logs.memid' , '=' , $user_id)
					->whereIN('tbl_reg_logs.status' , array('Active', 'Expired'))
					->orderBy('tbl_reg_logs.id' , 'DESC')
					->orderBy('tbl_reg_logs.status' , 'DESC')
					->get();
			
			
			
			foreach($logs as $r){
				///$res['IDs'][$r['id']] = $r['package_order'];
				if($r['status']=='Active'){
					$str = strtotime(date('Y-m-d',strtotime($r['enddate'])))-strtotime($GLOBALS['currDate']);				
					$daysLeft = floor($str/3600/24);
				}else{
					$daysLeft = 0;
				}
				
				$activatedBy = getCompanyFromService($r['f_product'])['com'];
				$details = array(
					"logID"    => $r['log_id'],///show renew/upgrade
					"isActive"    => $r['status']=='Active'?"y":"n",///show renew/upgrade
					"daysLeft"    => (int)$daysLeft,
					"outOf"        => $r['period_name']." months",
					"autoRenewal"=> $r['autoRenewal'],
					"packageId" => (int)$r['id'],
					"packageName" => $r['packageName'],
					"whatYouGet" => explode(',',$r['whatYouGet']),
					"amountPerMonth" => (double)$r['amountPerMonth'],                    
					"currency"=> $r['currency_code'],                    
					"invNo"=> $r['inv_no'],                    
					"licenses_cnt"=> $r['licenses_cnt'],                    
					"activatedBy"=> $activatedBy
				);
				//print_r($details);
				if($r['licenses_cnt']>1){
					
					$moreLogs = DB::table('tbl_reg_logs')
						->select("tbl_reg_logs.memid", 
								"tbl_members.name",
								DB::raw('(CASE WHEN send_email_to = "R" THEN email ELSE addtnl_email END) AS emailId'),
								DB::raw('(CASE WHEN send_sms_to = "R" THEN phoneno ELSE alternate_mob_no END) AS contacNo')
								)
						->leftJoin('tbl_members', 'tbl_members.id', '=', 'tbl_reg_logs.memid')
						->where('tbl_reg_logs.parent_id' , '=' , $r['log_id'])
						->whereIN('tbl_reg_logs.status' , array('Active', 'Expired'))
						->get();
					
					foreach($moreLogs as $mr){
						$details["licensesInformation"][] = array(
														"memId" => $mr['memid'],
														"name" => $mr['name'],
														"emailId" => $mr['emailId'],
														"contacNo" => $mr['contacNo']                     
													);
					}
					
				}
				
				$result['packageDetails'][]  = $details;
			}
			
			
			
			
			$code = 1001;
			$message = "Success";
			//include_once "/home/steelmin/public_html/api/storage/v2019/web/subcriptionDetails.php";
			
			return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));   
		}else{
			return new JsonResponse(array("status"=>array("code" => 2100, "message" => "Unauthorized action.")));
		}			
	}
	
	public function getAnnouncement(Request $request){
	    $result = array();
	    	$result_set = DB::table('tbl_announcement')->select('*')->take(15)->get();
	    	foreach($result_set as $res){
				$item = array(
					'date' => date("d-M-Y",strtotime($res['date_added_on']))." ".$res['time'],
					'commodity' => $res['commodity'],
					'type' => $res['type'],
					'title' => $res['title'],
					'download' => $res['file_url']
				);
				$result[] = $item;
			}
			/*$result = array(
				array(
						"date"=> "18-Mar-2018",
						"comodity" => 3,
						"type" => "correction",
						"title" => "text",
						"download" => "link"
					),
				array(
						"date"=> "18-Mar-2018",
						"comodity" => 3,
						"type" => "holiday",
						"title" => "15th aug",
						"download" => "link"
					)
			);

		$resourceType = "APP";		
		if ($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));*/
		
		//if($resourceType=='web'){
			$code = 1001;
			$message = "Success";
			
		//}
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $result));   
	}
	
	public function getMessgeBoard(Request $request){	
		if ($request->has('memid'))
		   //$memid = strtolower($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")));
                }
		   
		   
        $results = array();
		$result =DB::select("select t.id, t.title, t.description, t.url from tbl_message_board t where t.id not in (select `itemID` from tbl_message_board_skipped_by_memid where memid={$memid}) order by t.id DESC LIMIT 1");
		
		foreach($result as $row){
			$results[] = $row;
		}

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

		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $results));   
	}
	
	public function skipMessage(Request $request){
		if($request->has('memid')){
			//$memid = strtolower($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")));
                }
			
		}
		if($request->has('itemID'))
			$itemid = strtolower($request->input('itemID'));	
        $dat = array("f_datetime"=>date('Y-m-d H:i:s'),"memid"=>$memid,"itemID"=>$itemid);
		$skkip = DB::table('tbl_message_board_skipped_by_memid')->insert($dat);
		$code = 1001;
		$message = "Success";
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message), "data"=> $skkip));

	}
	public function logout(Request $request)
    {
		$resourceType = "app";
		
		$result = array();	
				
		if($request->has('resourceType'))
			$resourceType = strtolower($request->input('resourceType'));
		
		if($resourceType=='app'){
			if ($request->has('accessToken'))
			{
				$token = $request->input('accessToken');
				$user = new User();
				$auth = new authentication();
				$user_id = $auth->authToken($token);

				if ($user->userLogout($user_id)) {
					/**
					 * De-register user from notification table
					 */
					 DB::table('gcm_device')
						->where("user_id" , "=" , $user_id)
						->update(["user_id" => 0]);
				   /*  DB::table('gcm_device')
						->where("user_id" , "=" , $request->input('user_id'))
						->update(["user_id" => '']); */
				   // return new JsonResponse(array( "status#" => "1" , "message#" => "Successfully logout") , 200);
					return new JsonResponse(array("code" => 1001, "message" => "Successfully logout")); 
				}
				else {
					//return new JsonResponse(array( "status#" => "1" , "message#" => "Successfully logout") , 200);
					return new JsonResponse(array("code" => 1001, "message" => "Successfully logout")); 
					// doen by tarun on 2-june-2017 as ppl were facing issue when tryiong to logout
					//return new JsonResponse( array( "status#" => "1001" , "message#" => "Unauthorized action. Token access denied") , 403 ) ;
				}
			}
			else if ($request->has('username') && $request->has('password') )
			{
				$user = new User();
				if ( $user->userLogout_user_pass($request->input('username') , $request->input('password')) )	    
					return new JsonResponse(array("code" => 1001, "message" => "Successfully logout")); 
				else
					return new JsonResponse(array("code" => 1001, "message" => "Unauthorized action. Please request with token")); 
				//return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Please request with token") , 403 ) ;
			}
			else {
				
				return new JsonResponse(array("code" => 1001, "message" => "Unauthorized action. Username/password not matched")); 
				///return new JsonResponse( array( "status#" => "1002" , "message#" => "Unauthorized action. Username/password not matched") , 403 ) ;
			}
		}else{//web
		
		}
    }
	
	////
	public function requestDemoOrEnquiry(Request $request)
    {      
	    $result = array();
		$resourceType = 'web';
		if($request->has('resourceType') && $request->has('resourceType')!='')
			$resourceType = $request->input('resourceType');
	    
		$section='';//enquiry/demo
		if($request->has('section') && $request->has('section')!='')
			$section = $request->input('section');
		else{
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Invalid Section')));  
			return new JsonResponse(array("status#" => 1, "message" => "Invalid Section")); 
		}
		
	    $email='';
		if($request->has('email') && $request->has('email')!=''){
			$email = $request->input('email');
		}else{
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Email Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Email Required")); 
		}
		
		$isdCode='';
		if($request->has('isd_code') && $request->has('isd_code')!='')
			$isdCode = $request->input('isd_code');
		
		$mobileNumber='';
		if($request->has('mobileNumber') && $request->has('mobileNumber')!='')
			$mobileNumber = $request->input('mobileNumber');
		else{
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Phoneno Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Phoneno Required")); 
		}
		
		$requirement='';//demo
		if($request->has('requirement') && $request->has('requirement')!='')
			$requirement = $request->input('requirement');
		
		$name='';//enquiry
		if($request->has('name') && $request->has('name')!='')
			$name = $request->input('name');
		elseif($section=='enquiry'){
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Name Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Name Required")); 
		}
		
		$enquiryOn='';//enquiry
		if($request->has('enquiryOn') && $request->has('enquiryOn')!='')
			$enquiryOn = $request->input('enquiryOn');
		elseif($section=='enquiry'){
			//return new JsonResponse(array("status#"=>array("code" => 2100, "message" => 'Intrested topic is Required')));  
			return new JsonResponse(array("status#" => 1, "message" => "Intrested topic is Required")); 
		}
		
		$address='';//enquiry
		if($request->has('address') && $request->has('address')!='')
			$address = $request->input('address');		

			$ipAddress = $_SERVER['REMOTE_ADDR'];	
			//DB::enableQueryLog(); 
			$dbresult = DB::table($_ENV['USER_TABLE'])
				->select('id')
				->where(function($q) use ($email) {
							$q->where('email' ,$email)
							->orWhere('addtnl_email' ,$email)
							->orWhere('username' ,$email);
						})
				->orWhere(function($q) use ($mobileNumber) {
							$q->where('phoneno' ,$mobileNumber)
							->orWhere('alternate_mob_no' ,$mobileNumber)
							->orWhere('username' ,$mobileNumber);
						})
				->get();
			//dd(DB::getQueryLog());
			if (count($dbresult) == 0 ){///invalid or new user 
				$cntry_id=0;
				if($isdCode){
					$expVal = explode(" ", $isdCode);		
					$std_code = end($expVal);				
					$isdCode = '+'.trim($std_code, '+');
					
					
					$result = DB::table('tbl_country')
						->select('id')
						->where('std_code', '=', $isdCode)
						->first();
					if(count($result)>0){
						$cntry_id = $result['id'];
					}
				}
				
				$type='new';
				$newUser['username'] = $email;
				$newUser['phoneno'] = $mobileNumber;
				$newUser['isd_code'] = $isdCode;
				$newUser['country'] = $cntry_id;
				$newUser['password'] = '123456';
				$newUser['ol_be'] = $section;
				$newUser['main_source'] = $resourceType.' : '. $section;
				$newUser['source_from'] = $section;
				$newUser['address'] = $address;
				$newUser['ipaddress'] = $ipAddress;
				$newUser['date'] = $GLOBALS['currDateTime'];
				$newUser['primary_source'] = $section=='demo'?'CAMP112':'CAMP139';
				$newUser['lead_type'] = 'A1';
				
				$memid = DB::table('tbl_members')->insertGetId($newUser);

			}else{
				$memid = $dbresult[0]['id'] ;
				$type='old';				
			}
			require_once("/home/steelmin/public_html/hf.php");
			$lead_type='A1';$mood='';$fudate='';
				if($type=='old'){
					//$lead_type = getLastLeadType($memid, $service_type=$f_product);
					$leadtypeArr = getLastLeadType($memid, $service_type='W',$dflag='true');
					if(isset($leadtypeArr['lead_type']) && $leadtypeArr['lead_type']!='')
						$lead_type = $leadtypeArr['lead_type'];
					if(isset($leadtypeArr['mood'])  && $leadtypeArr['lead_type']!='')
						$mood = $leadtypeArr['mood'];
					if(isset($leadtypeArr['fudate']) && $leadtypeArr['fudate']!='')
						$fudate = $leadtypeArr['fudate']; 
					
					if($lead_type=='A5' || $lead_type=='B5')
						$lead_type='A11';
				}
				
				$rm_arr =getRMForRoutingProcess($memid, $company_name='steelmint', $lead_type); 
				
				$tbl_reg_logs=array(
					'memid'=>$memid,					
					'startdate'=>$GLOBALS['currDate'],
					'enddate'=>$GLOBALS['currDate'],
					'f_time'=>$GLOBALS['currTime'],
					'f_product'=>'W',
					'f_tenure'=>'One Day',
					'status'=>'Pending',
					'selected_products'=>$section,
					'comments'=>'From : '. $section,
					'created_on'=>$GLOBALS['currDateTime'],
					'lead_type'=>$lead_type,
					'fudate'=>$fudate,
					'rm'=>$rm_arr['rm_id'],
					'subrm'=>$rm_arr['subrm_id'],
					'mood'=>$mood,
					'pipeline_status'=>'New',
					'routing_status'=>$lead_type,
					'first_log_id' => $rm_arr['first_log_id']
				);
			
				//print_r($tbl_reg_logs);
				try{
					$_log_id = DB::table('tbl_reg_logs')->insertGetId($tbl_reg_logs);
					updateTbltbl_updated_reg_logs($memid);					
				} catch (QueryException $e) {
					dd($e);
				}
				
				foreach($request->all() as $key=>$subvalue)
				{	
					$comments = $comments." $key => ".$subvalue." <br /> ";
				}
				
				$comments .= "<br> Tried to register in ".$resourceType." <br /> ";
				$comments .= " ip => ".$ipAddress." <br /> ";
		
		
			DB::table($_ENV['COMMENTS_TABLE'])->insert([ 'memid' => $memid,
							'f_date' => $GLOBALS['currDate'],
							'f_time' => $GLOBALS['currTime'],
							'comments' => "Request Service Type : ".$comments,
							'created_by' => 'self',
							'comments_for' => $section]);	
		
		//sendBULKsms($phnno, $msg, '', $senderid = 'MINTTT');
		$code = 1001;
		$message = "Successfully Sent";		
		
		
	   //, "data"=> $result;
		//return new JsonResponse(array("status#"=>array("code" => $code, "message" => $message)));   
		return new JsonResponse(array("status#" => 1, "message" => $message)); 
    }
	
	public function autoRenew(Request $request)
	{
		
		$result = array();
		$resourceType = 'app';
		if($request->has('resourceType') && $request->has('resourceType')!='')
			$resourceType = $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');
			    $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) {
			if(!$request->has('logID')) {//tbl_reg_log.id
				return new JsonResponse(array("status"=>array("code" => 2001, "message" => "invalid logID for renew!")));
			}else{
				$logID = $request->input('logID');
				$autoRenewal = $request->input('autoRenewal');
				//$table_name = 'tbl_reg_logs':'tbl_sm_events_payment_details';
				$table_name = 'tbl_reg_logs';
				DB::table($table_name)
					->where('id', '=', $logID )
					->update( [ 'autoRenewal' => $autoRenewal , 'autoRenewal_activatedOn'=> $GLOBALS['currDateTime']]);
					
				$code = 1001;
				$message = "Successfully Saved";
			}
		}else{
			//return new JsonResponse(array("code" => 2100, "message" => "Unauthorized action."));
			$code = 2100;
			$message = "Unauthorized action";
		}
		
	   return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
	   //return new JsonResponse(array("code" => $code, "message" => $message));
    }
}
