<?php
namespace App\Http\Controllers\v2019;
/* 
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Auth\authentication;
use DB ; */

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

use Validator;
use Session;

class IosFlowController extends Controller
{
    public $appType = 'SM' ;
	public function __construct(Request $request) {
        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;			
        }
		$this->appType = 'SM';
		if($request->has('appType') && $request->input('appType') == true) {
            $this->appType = $request->input('appType');		
        } elseif($request->has('filters')){
			 $filter = $request->input('filters');
			 if(!empty($filter['app_type'])){
					$this->appType = 'CM';
			 }
		} elseif($request->has('app_type') && $request->input('app_type') == true) {
            $this->appType = $request->input('app_type');		
        }
		
	}


    public function make_seed()
    {
       list($usec, $sec) = explode(' ', microtime());
       return $sec + $usec * 1000000; 
    }
    
	public function fromContinue1(Request $request){
        include_once "/home/steelmin/public_html/inc/config1.php";
        

        $data = $request->input('Recpt');
        $t['f_data']=$data;
        $t['f_dt']=date('Y-m-d');
        //echo $reg_log_id = DB::table('tbl_try1')->insertGetId($t);        
        	return new JsonResponse(array("status"=>array("code" => 1001, "message" =>"dump"), "data"=>$data));
	}

	public function chkTokenToMemid(){
	    
	    $rct = '{"receipt":{"receipt_type":"Production","app_item_id":885759135,"receipt_creation_date":"2021-12-23 04:55:18 Etc\/GMT","bundle_id":"com.steelmint","original_purchase_date":"2021-12-19 03:10:46 Etc\/GMT","in_app":[{"quantity":"1","purchase_date_ms":"1639898185000","expires_date":"2022-01-19 07:16:25 Etc\/GMT","expires_date_pst":"2022-01-18 23:16:25 America\/Los_Angeles","is_in_intro_offer_period":"false","transaction_id":"240001071419924","is_trial_period":"false","original_transaction_id":"240001071419924","purchase_date":"2021-12-19 07:16:25 Etc\/GMT","product_id":"com.steelmint.PriceOnly1Month","original_purchase_date_pst":"2021-12-18 23:16:26 America\/Los_Angeles","in_app_ownership_type":"PURCHASED","original_purchase_date_ms":"1639898186000","web_order_line_item_id":"240000460582726","expires_date_ms":"1642576585000","purchase_date_pst":"2021-12-18 23:16:25 America\/Los_Angeles","original_purchase_date":"2021-12-19 07:16:26 Etc\/GMT"}],"adam_id":885759135,"receipt_creation_date_pst":"2021-12-22 20:55:18 America\/Los_Angeles","request_date":"2021-12-23 04:55:44 Etc\/GMT","request_date_pst":"2021-12-22 20:55:44 America\/Los_Angeles","version_external_identifier":845020626,"request_date_ms":"1640235344188","original_purchase_date_pst":"2021-12-18 19:10:46 America\/Los_Angeles","application_version":"0","original_purchase_date_ms":"1639883446000","receipt_creation_date_ms":"1640235318000","original_application_version":"0","download_id":500985026388365168},"section":"Steelmint","accessToken":"CPLzOGe4QacT2CIsg4HrmbayGNQQaRWk","fcmToken":null,"physical_id":"C0C7F058-B712-4779-82DA-D15875CF9D1D","device_Type":"ios"}';
	    
	    include_once "/home/steelmin/public_html/inc/config1.php";
        $data = json_decode($rct, true);
        echo "<pre>";
        print_r($data);
        
		$reciept = $data['receipt'];
		$physical = $data['fcmToken'];
		$my_array = serialize($reciept);
		$mem_id = 0;
		if ($data['accessToken'] && $data['accessToken']!='') {  
			$token = $data['accessToken'];
			$auth = new authentication();
			$mem_id = $auth->authToken($token,$this->appType);
		}	
		echo 'm:' . $mem_id;
		if( '' == $physical )
			$physical = 'NA';
		if( '' == $my_array )
			$my_array = 'NA';
		///saving tbl_ios_reciept
		DB::table('tbl_ios_reciept')->insert(['device_id'=>$physical, 'user_id'=>$mem_id,'reciept'=> $my_array,'created_at'=>date("Y-m-d H:i:s")]);
	    include_once "/home/steelmin/public_html/inc/desconfig.php";
    }


	public function fromContinue_test(Request $request){
		include_once "/home/steelmin/public_html/inc/config1.php";
		if($request->has('Recpt')){
             $data = $request->input('Recpt');
			  $t['f_data']=$data;
		 }else{
			$t['f_data']= implode('/*/', $request->all());
		 }		
		 
		 $data = json_decode($request->input('Recpt'), true);
		if( count($data) == 0 )
			$data = $request->input('Recpt');
		
		
        // $data = json_decode($request->input('Recpt'), true);
		$reciept = $data['receipt'];
		$physical = $data['fcmToken'];
		$my_array = serialize($reciept);
		$mem_id = 0;
		if ($data['accessToken'] && $data['accessToken']!='') {  
			$token = $data['accessToken'];
			$auth = new authentication();
			$mem_id = $auth->authToken($token,$this->appType);
		}		
		
		if( '' == $physical )
			$physical = 'NA';
		
		///saving tbl_ios_reciept
		DB::table('tbl_ios_reciept')->insert(['device_id'=>$physical, 'user_id'=>$mem_id,'reciept'=> $my_array,'created_at'=>date("Y-m-d H:i:s")]);
		include_once "/home/steelmin/public_html/inc/desconfig.php";
		
/* 		 if($request->has('Recpt')){
              $data = $request->input('Recpt');
        $t['f_data']=$data;
		 }else{*/
			//$t['f_data']= implode('/*/', $request->all());
		 /*}
        $t['f_gateway_name']=date('Y-m-d');
         $reg_log_id = DB::table('tbl_try')->insertGetId($t);        
        return new JsonResponse(array("status"=>array("code" => 1001, "message" =>"dump"), "data"=>$data)); */
	}

	public function fromContinue(Request $request){
        include_once "/home/steelmin/public_html/inc/config1.php";

/**/
		if($request->has('Recpt')){
			$data = $request->input('Recpt');
			$t['f_data']=$data;
		}else{
			$t['f_data']= implode('/*/', $request->all());
		}
		$t['f_gateway_name']=date('Y-m-d H:i:s');
		
		$t['relation_ids']="iosFlowController.php -> fromContinue(T)->".$this->appType;
		
		//$reg_log_id = DB::table('tbl_try')->insertGetId($t);    
/**/


        $data = json_decode($request->input('Recpt'), true);
		
		if( count($data) == 0 )
			$data = $request->input('Recpt');
		$reciept = $data['receipt'];
		$physical = $data['fcmToken'];
		$my_array = serialize($reciept);
		$mem_id = 0;
		if(isset($data['filters'])){
			 $filter = $data['filters'];
			 if(!empty($filter['app_type'])){
					$this->appType = 'CM';
			 }
		}
		
		if ($data['accessToken'] && $data['accessToken']!='') {  
			$token = $data['accessToken'];
			$auth = new authentication();
			$mem_id = $auth->authToken($token,$this->appType);
		}
		////$reg_log_id = DB::table('tbl_try')->insertGetId($t);
		if( '' == $physical )
			$physical = 'NA';
		if( '' == $my_array )
			$my_array = 'NA';
		///saving tbl_ios_reciept
		DB::table('tbl_ios_reciept')->insert(['device_id'=>$physical, 'user_id'=>$mem_id,'reciept'=> $my_array,'created_at'=>date("Y-m-d H:i:s")]);

        include_once "/home/steelmin/public_html/inc/desconfig.php";
		return new JsonResponse(array("status"=>array("code" => 1001, "message" => "Success")));
	}
	
	public function fromContinue_20_10_2020(Request $request){
        include_once "/home/steelmin/public_html/inc/config1.php";
	
        $data = json_decode($request->input('Recpt'), true);
		$reciept = $data['receipt'];
		$physical = $data['fcmToken'];
		$my_array = serialize($reciept);
		$mem_id = 0;
		if ($data['accessToken'] && $data['accessToken']!='') {  
			$token = $data['accessToken'];
			$auth = new authentication();
			$mem_id = $auth->authToken($token,$this->appType);
		}			
		///saving tbl_ios_reciept
		DB::table('tbl_ios_reciept')->insert(['user_id'=>$mem_id,'reciept'=> $my_array,'created_at'=>date("Y-m-d H:i:s")]);

        include_once "/home/steelmin/public_html/inc/desconfig.php";
		return new JsonResponse(array("status"=>array("code" => 1001, "message" => "Success")));
		
		
        include_once('/home/steelmin/public_html/hf.php');
        include_once('/home/steelmin/public_html/steeladmin/invoices/invoice_function_sm.php');
        if($request->has('Recpt')){
//DB::table('tbl_try')
//	->insert(['f_data'=>"step 3".'--'.$mem_id,'f_gateway_name'=>date("Y-m-d H:i:s")]);

        //if($result){
			///$data = json_decode($result['f_data'], true); 
			$data = json_decode($request->input('Recpt'), true);
			
			if(isset($data['logID'])){///ON IAP
//DB::table('tbl_try')
//	->insert(['f_data'=>"step 4".'--'.$mem_id,'f_gateway_name'=>date("Y-m-d H:i:s")]);
			
				if($data['status']=='success'){
				
					$logID = $data['logID'];
					//$recieptRes = $data['receipt'];
					/////$reciept = $data['receipt'];
					
					$token_app = $data['tokenInApp'];
					$physical = $data['physical_id'];
					$pymDtls=$data['device_Type'];
					
					$f_currency=$data['product_currency'];
					$pymtMode='in-app purchase';
					$amtPaid=$data['Product_amount'];
					///srand($this->make_seed());
					/* if(!isset($recieptRes['receipt'])){
						$code = 1001;
						$message = "Successfully Saved";
					}else{ 
						$reciept =  $recieptRes['receipt'];*/
				
					$store=array(); 
					///if(isset($reciept["in_app"]) && is_array($reciept["in_app"])){
					if(isset($data["in_app"]) ){
						
						$t=array();$mem_id=0;$apple_id='';
						
						$result = DB::table("tbl_reg_logs")->select("memid")->where("id","=",$logID)->first();
						$mem_id = $result["memid"];
				
						//$size = count($reciept["in_app"]);
						$in_app[] = $data["in_app"];
						//foreach($reciept["in_app"] as $k=>$v){
						foreach($in_app as $k=>$v){

							$apple_id = $v["original_transaction_id"];
							/////$t['datepay'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							//$t['enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
							$t['apple_startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							$t['apple_enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));

							//$t['status'] = strtotime($t["apple_enddate"]) > strtotime(date("Y-m-d H:i:s")) ? "Active" : "Expired";
							$t['status'] = strtotime(date("Y-m-d", strtotime($t["apple_enddate"]))) >= strtotime(date("Y-m-d")) ? "Active" : "Expired";
							///ECHO '<pre>'.$t['status'].'--'.date("Y-m-d H:i:s", strtotime($t["apple_enddate"])).'--'.date("Y-m-d H:i:s").'--'.'</pre>';
							/////$t['paymentstatus']='Paid';
							/////$t['acc_ver_pending'] = 1;
							$t['f_currency'] = $f_currency;
							///$t['startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							$t['pymDtls'] = $pymDtls;
							$t['f_product']='MA';
							//$t['inv_no'] = "tmp_".rand();
							$t['f_tenure']='One Year';
							///$t['amtPaid'] = $k == $size-1 ? $amtPaid:"";
							////$t['amtPaid'] = $amtPaid;
							//$t['selected_products']='Standard';
							//$t['created_on']=date("Y-m-d H:i:s");
							//$t['nb_order_no'] = $v["purchase_date_ms"];
							$t['nb_order_no'] = $v["transaction_id"];
							$t['pymtMode'] = $pymtMode;
							$t['apple_package_ID'] = $v["product_id"];
						   
						   if($t['status']=="Expired")
							   unset($t['status']);
							
							//$result = DB::table("tbl_reg_logs")->leftJoin("tbl_members","tbl_reg_logs.memid","=","tbl_members.id")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid')->where("tbl_reg_logs.nb_order_no","=",$v["purchase_date_ms"])->where("tbl_members.apple_id","=",$apple_id)->first();//->count()
							//DB::enableQueryLog(); //
							$result = DB::table("tbl_reg_logs")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid')->where("tbl_reg_logs.nb_order_no","=",$v["transaction_id"])->where("tbl_reg_logs.memid","=",$mem_id)->first();//->count()
							//dd(DB::getQueryLog());

							if(count($result)>0){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
								///$mem_id = $result["memid"];
								$log_id = $result["log_id"];
								$dontExpireByApple = $result["dontExpireByApple"];
								
								if($logID==$log_id){//update
									if($dontExpireByApple==0 && $t['status']=="Expired"){
										/////$t['status']="Expired";
										/////DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									}elseif($result['status']!="Expired")
										$t['status']=$result["status"];///don't Expired till log date
									//DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
								}else{//insert
									/* if($result['status']=='Active' && $t['status']=='Active'){//update
										
									} */
									$t['memid'] = $mem_id;
									
									$t['selected_products']="Mobile App";
									$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
									if($resultPackages){
										$t['selected_products']='GroupID:'.$resultPackages['group_id'];
										
										$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
										if($resultPackagesCC)
											$t['selected_products']=$resultPackagesCC['id'];//Package ID
									}
									if($dontExpireByApple==0 && $t['status']=="Expired"){
										/////DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									}
									///$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
									///DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
									///DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
								}
								
								$t['memid'] = $mem_id;
							}else{//insert
								/* $result = DB::table("tbl_reg_logs")->select("memid")->where("id","=",$logID)->first();
								$mem_id = $result["memid"]; */
								
								
								$t['memid'] = $mem_id;
								$t['startdate'] = $t['apple_startdate'];
								$t['enddate'] = $t['apple_enddate'];
								
								/* $t['selected_products']="Mobile App";
								$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
								if($resultPackages){
									$t['selected_products']='GroupID:'.$resultPackages['group_id'];
									
									$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
									if($resultPackagesCC)
										$t['selected_products']=$resultPackagesCC['id'];//Package ID
								} */
								//DB::enableQueryLog();
								$resultLog = DB::table("tbl_reg_logs")->select("id", "selected_products")->where("memid","=",$mem_id)->where(DB::raw("(STR_TO_DATE(created_on,'%Y-%m-%d'))"), ">=", date("Y-m-d"))->where("apple_package_ID","=",$t['apple_package_ID'])->orderBy('created_on' , 'asc')->first();
								//dd(DB::getQueryLog()); 
								//print_R($resultLog);
								if($resultLog){//update
									$log_id = $resultLog["id"];
									///$dontExpireByApple = $result["dontExpireByApple"];
									///echo $logID.'==.'.$log_id.'-'.$t['status'];
									if($logID==$log_id && $t['status']=='Active'){
										DB::table('tbl_reg_logs')->where("id", "=" , $logID)->update($t);
									
										DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
									}else{
										/* $t['created_on']=date("Y-m-d H:i:s");
										$t['f_time']=date("H:i:s");
										$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
										DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]); */
										//new code after single row in responce
										DB::table('tbl_reg_logs')->where("id", "=" , $logID)->update($t);
									
										DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
									}
									
								}/* else{
									$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
									DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
								} */
								///$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
								//DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
								
								
								///DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
							} 
						}
						
						updateTbltbl_updated_reg_logs($mem_id);
						
						if($logID){
							///$stats = "Successful Payment <br />";
							$msgsadmin ='
									<table width="600" border="0" cellspacing="0" cellpadding="0" > 
										<tr> 
											<td><img src="https://www.steelmint.com/images/logo.gif"></td>
											<td width="293">&nbsp;</td> 
										</tr> 
										<tr> 
											<td colspan="2" align="left"><p><br />Hi,<br><br><b>Membership Id : '.$mem_id.'</b> has been registered for ios app with <b>Successful Payment</b> </p> 
											</td> 
										</tr> 										
									</table>
								';
							$sender="SteelMint";
							$sender_email="info@steelmint.com";
							$sender_url=BASEURL."";
							/* $ureg_res = mysql_query("select (select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.rm) as relMngr,
										(select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.subrm) as subRelMngr from tbl_updated_reg_logs as ureg where memid=$mem_id and services in ('W','MA','S','E') limit 1");
							$ureg_row = mysql_fetch_array($ureg_res); */
							$ureg_row = DB::select("select (select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.rm) as relMngr,
										(select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.subrm) as subRelMngr from tbl_updated_reg_logs as ureg where memid=$mem_id and services in ('W','MA','S','E') limit 1");
							
							if( $ureg_row['relMngr'] != '') 
								$rmEmail = $ureg_row['relMngr'];
							if(  $ureg_row['subRelMngr'] != '' ) 
								$rmEmail =$ureg_row['subRelMngr'];
							include_once ('/home/steelmin/public_html/hf.php');
							include_once ('/home/steelmin/public_html/mf.php');
							//sendSMMail($msgsadmin, 'mohan@theitbooth.com,akash.dhomne@theitbooth.com', "", "Registration from inAPP", $sender_email, $sender, $sender_email);
							sendSMMail($msgsadmin, $rmEmail . ',accounts@steelmint.com,virendra@steelmint.com,info@steelmint.com', "", "Registration from inApp", $sender_email, $sender, $sender_email);
						}
						
						$code = 1001;
						$message = "Successfully Saved";
					}else{
						$code = 2001;
						$message = "Invalid  Request";
					}
				}else{///failure
					if($data['logID']){
						
						$userLogRes = DB::table("tbl_reg_logs")->select("memid")->where("id","=",$data['logID'])->first();
						$memid = $userLogRes["memid"];
						$userRes = DB::table("tbl_members")->select(DB::raw('(CASE WHEN send_email_to = "R" THEN email ELSE addtnl_email END) AS emailId'))->where("id","=",$memid)->first();
						
						$failedData = array(
							"paymentstatus"=>"Failed",
							"pymtMode"=>"in-app purchase",
							//"offline_attachment"=>''
							"datepay"=>'0000-00-00'
						);
						DB::table('tbl_reg_logs')->where("id" , "=" , $data['logID'])->update($failedData);
						///comments
						$failedComment = array(
							'f_date'	=>	$GLOBALS['currDate'], 
							'f_time'	=>	$GLOBALS['currTime'], 
							'comments'	=>	'iOS in-app purchase payment failed, logid:'.$data['logID'], 
							'memid'	=>	$memid, 
							'comments_for'	=>	'MA', 
							'created_by'	=>	'auto after in-app pymt failure'
						);
						
						DB::table('tbl_comments')->insert($failedComment);						
						//include_once ('/home/steelmin/public_html/hf.php');
						include_once ('/home/steelmin/public_html/mf.php');
						if($userRes['emailId'])
							linkSentAfterPymtFailureV2019($userRes['emailId'],$data['logID']);
					}
					$code = 1001;
					$message = "payment failed";
				}
				///}
			}else{///on restore and app start
				//$reciept = $data['recipt');
//DB::table('tbl_try')
//	->insert(['f_data'=>"step 5".'--'.$mem_id,'f_gateway_name'=>date("Y-m-d H:i:s")]);
				
				///$recieptRes = $data['receipt'];
				$reciept = $data['receipt'];
				//return new JsonResponse(array("status"=>array("code" => 1001, "message" => $reciept)));
				///if(!isset($recieptRes['receipt'])){
				if(!isset($data['receipt'])){
//DB::table('tbl_try')
//	->insert(['f_data'=>"step 6".'--'.$mem_id,'f_gateway_name'=>date("Y-m-d H:i:s")]);
					$code = 2001;
					$message = "Invalid  Request";
				}else{
//DB::table('tbl_try')
//	->insert(['f_data'=>"step 7".'--'.$mem_id,'f_gateway_name'=>date("Y-m-d H:i:s")]);
					
					//$token_app = $data['tokenInApp'];
					$token_app = $data['accessToken'];
					$physical = $data['physical_id'];
					$pymDtls=$data['device_Type'];
					$pymtMode='in-app purchase';
					$my_array = serialize($reciept);
					/* $f_currency=$data['product_currency'];
					
					$amtPaid=$data['Product_amount'];
					srand($this->make_seed()); */
					if ($data['accessToken'] && $data['accessToken']!='') {  
						$token = $data['accessToken'];
						$auth = new authentication();
						$mem_id = $auth->authToken($token,$this->appType);
						
						///saving tbl_ios_reciept
						
						DB::table('tbl_ios_reciept')->insert(['device_id'=>$physical,'user_id'=>$mem_id,'reciept'=> $my_array]);
						///end saving tbl_ios_reciept
						
						$store=array(); 
						$serviceStatus='';
						if(isset($reciept["in_app"]) && is_array($reciept["in_app"])){
							$t=array();$apple_id='';
						   $size = count($reciept["in_app"]);
						   
							foreach($reciept["in_app"] as $k=>$v){ 
							   $apple_id = $v["original_transaction_id"];
							   $t['datepay'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								//$t['enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
								$t['apple_startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								$t['apple_enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
							
								/////$t['status'] = strtotime($t["apple_enddate"]) > strtotime(date("Y-m-d H:i:s")) ? "Active" : "Expired";
								$t['paymentstatus']='Paid';
								$t['acc_ver_pending'] = 1;
								///////$t['f_currency'] = $f_currency;
								///$t['startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								///$t['pymDtls'] = $pymDtls;
								$t['f_product']='MA';
								//$t['inv_no'] = "tmp_".rand();
								$t['f_tenure']='One Year';
								//$t['amtPaid'] = $k == $size-1 ? $amtPaid:"";
								//$t['selected_products']='Standard';
								$t['created_on']=date("Y-m-d H:i:s");
								//$t['nb_order_no'] = $v["purchase_date_ms"];
								$t['nb_order_no'] = $v["transaction_id"];
								$t['pymtMode'] = $pymtMode;
								$t['apple_package_ID'] = $v["product_id"];

							   if($t['status']=="Expired")
								   unset($t['status']);
							   
								$result = DB::table("tbl_reg_logs")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid','selected_products')->where("tbl_reg_logs.nb_order_no","=",$v["transaction_id"])->first();//->count()
							  /// print_r($result );
							   //->where("memid","=",$mem_id)
								if($result){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
									$log_id = $result["log_id"];
									$dontExpireByApple = $result["dontExpireByApple"];
									if($dontExpireByApple==0 && $t['status']=="Expired"){
										/////$t['status']="Expired";
										/////DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									}elseif($result['status']!="Expired")
										$t['status']=$result["status"];///don't Expired till log date
									$packageNameId=$result["selected_products"];
									
									//update memid if 0
									if($result['memid']!=$mem_id)
									{
										$updatMID['memid'] = $mem_id;									
										DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($updatMID);
									}
									
									$resultPackages = DB::table("tbl_packages")->select("group_id","id","packageName")->where("id","=",$packageNameId)->first();
									$packageName=$resultPackages["packageName"];
									//DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
								}else{									
									
									
									$t['memid'] = $mem_id;
									$t['startdate'] = $t['apple_startdate'];
									$t['enddate'] = $t['apple_enddate'];
									
									$t['selected_products']="Mobile App";
									$resultPackages = DB::table("tbl_packages")->select("group_id","id","packageName")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
									if($resultPackages){
										//$t['selected_products']='GroupID:'.$resultPackages['group_id'];
										$t['selected_products']=$resultPackages['id'];
										$packageName=$resultPackages['packageName'];
										
										/* $resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
										if($resultPackagesCC)
											$t['selected_products']=$resultPackagesCC['id'];//Package ID */
									}
									
									$result = DB::table("tbl_reg_logs")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid','selected_products')->where("tbl_reg_logs.f_tenure","<>",'Free Trial')->where("tbl_reg_logs.status","=",'Active')->where("tbl_reg_logs.memid","=",$mem_id)->whereIn("tbl_reg_logs.f_product",array('MA'))->first();//'W',
									if($result){
										//if(strtotime($result['startdate'])==strtotime('Y-m-d', strtotime($t['apple_startdate'])) && strtotime($result['enddate'])==strtotime('Y-m-d', strtotime($t['apple_enddate']))){
										if(1){
										//- if active log exists in tbl_reg_logs AND we get a paid receipt AND start, end date matches exactly then update transaction id
											///$t["nb_order_no"] = $v["transaction_id"];
											if('Active'==$t['status']){
												$updatMID['nb_order_no'] = $v["transaction_id"];						
												DB::table('tbl_reg_logs')->where("id", "=" , $result['log_id'])->update($updatMID);
											}
										}else{
											//- if active log exists in tbl_reg_logs AND we get a paid receipt BUT start, end date NOT matches exactly then dont do any action
										}
									}elseif('Active'==$t['status']){
										//- if no active log exists in tbl_reg_logs but we get a paid receipt then create new log in reg_logs
										$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
										
										DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);							
									}
									
									DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
																											
								}	
									if('Active'==$t['status']){
										$serviceStatus = "Paid log Exists for your Apple ID: Package Name:".$packageName.", Start Date:".$t['startdate'].", End Date:".$t['enddate']."";
									}								
							}
							
						
							//$inv_file = generateInvoice($company='coalmint', $reg_logs_id, 'online');
							updateTbltbl_updated_reg_logs($mem_id);
						   
						   $code = 1001;
							IF($serviceStatus!='')
								$message = $serviceStatus ;
							ELSE
								$message = "No paid log found for your Apple ID";
						} else{
//DB::table('tbl_try')
//	->insert(['f_data'=>"step 8".'--'.$mem_id,'f_gateway_name'=>date("Y-m-d H:i:s")]);
							$code = 2001;
							$message = "Invalid  Request";
						}
						
					}elseif(0){///when no accesstoken =>  nothing is happening
						$mem_id = 0;
						
						DB::table('tbl_ios_reciept')->insert(['device_id'=>$physical,'reciept'=> $my_array]);
						
						$store=array(); 
						$serviceStatus='';
						if(isset($reciept["in_app"]) && is_array($reciept["in_app"])){
							$t=array();$apple_id='';
						   $size = count($reciept["in_app"]);
						   
							foreach($reciept["in_app"] as $k=>$v){ 
							   $apple_id = $v["original_transaction_id"];
							   $t['datepay'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								//$t['enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
								$t['apple_startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								$t['apple_enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
							
								$t['status'] = strtotime($t["apple_enddate"]) > strtotime(date("Y-m-d H:i:s")) ? "Active" : "Expired";
								$t['paymentstatus']='Paid';
								$t['acc_ver_pending'] = 1;
								/////$t['f_currency'] = $f_currency;
								///$t['startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								///$t['pymDtls'] = $pymDtls;
								$t['f_product']='MA';
								//$t['inv_no'] = "tmp_".rand();
								$t['f_tenure']='One Year';
								//$t['amtPaid'] = $k == $size-1 ? $amtPaid:"";
								//$t['selected_products']='Standard';
								$t['created_on']=date("Y-m-d H:i:s");
								///$t['nb_order_no'] = $v["purchase_date_ms"];
								$t['nb_order_no'] = $v["transaction_id"];
								$t['pymtMode'] = $pymtMode;
								$t['apple_package_ID'] = $v["product_id"];

							   
								$result = DB::table("tbl_reg_logs")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid','selected_products')->where("tbl_reg_logs.nb_order_no","=",$v["transaction_id"])->first();//->count()
							   
								if($result){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
									$log_id = $result["log_id"];
									$dontExpireByApple = $result["dontExpireByApple"];
									if($dontExpireByApple==0 && $t['status']=="Expired"){
										$t['status']="Expired";
										DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									}else
										$t['status']=$result["status"];///don't Expired till log date
									$mem_id=$result["memid"];
									$packageNameId=$result["selected_products"];
									//DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									$resultPackages = DB::table("tbl_packages")->select("group_id","id","packageName")->where("id","=",$packageNameId)->first();
									$packageName=$resultPackages["packageName"];
								}else{
									$t['memid'] = $mem_id;///need to work
									$t['startdate'] = $t['apple_startdate'];
									$t['enddate'] = $t['apple_enddate'];
									
									$t['selected_products']="Mobile App";
									$resultPackages = DB::table("tbl_packages")->select("group_id","id","packageName")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
									if($resultPackages){
										//$t['selected_products']='GroupID:'.$resultPackages['group_id'];
										$t['selected_products']=$resultPackages['id'];
										$packageName=$resultPackages['packageName'];
										
										/* $resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
										if($resultPackagesCC)
											$t['selected_products']=$resultPackagesCC['id'];//Package ID */
									}
									
									if('Active'==$t['status']){
										$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
										DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->update(["first_log_id" => $reg_log_id ]);
									}
									/* if($memid){
										$usrMeM = DB::table("tbl_members")->select("device_token")->where("id" , "=" , $mem_id)->first();
									} */
										
									////DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
									
								}						
								
									if('Active'==$t['status']){
									
										$serviceStatus = "Paid log Exists for your Apple ID: Package Name:".$packageName.", Start Date:".$t['startdate'].", End Date:".$t['enddate']."";
									}
								
							}
							
						
							//$inv_file = generateInvoice($company='coalmint', $reg_logs_id, 'online');
							updateTbltbl_updated_reg_logs($mem_id);
						   
						   $code = 1001;
							//$message = "Successfully Saved";
							IF($serviceStatus){
								$token = 'testaccessToken'.date('ymdhi');
								return new JsonResponse(array("status"=>array("code" => $code, "message" => $serviceStatus, "accessToken" => $token)));
							}else{
								$message = "No paid log found for your Apple ID";
								return new JsonResponse(array("status"=>array("code" => $code, "message" => $serviceStatus, "accessToken" => "")));
							}
						} else{
							$code = 2100;
							$message = "Access token is invalid or has expired.";
						}
					}else{///added on 16 jun 2020
						$code = 2100;
						$message = "Access token is invalid or has expired.";
					}
				}
			}
			
		}else{
//DB::table('tbl_try')
//	->insert(['f_data'=>"step 580".'--'.$mem_id,'f_gateway_name'=>date("Y-m-d H:i:s")]);
			$code = 2001;
			$message = "Invalid  Request";
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }


	public function fromContinueV201920052020(Request $request){
        include_once "/home/steelmin/public_html/inc/config1.php";
        

        /* $data = $request->input('Recpt');
        $t['f_data']=$data;
        echo $reg_log_id = DB::table('tbl_try1')->insertGetId($t);        
        	return new JsonResponse(array("status"=>array("code" => 1234, "message" =>"dump")));
      */
		/* $data = $request->input('Recpt');
        $t['f_data']=$data;
        $t['f_dt']=date('Y-m-d H:i');
        $reg_log_id = DB::table('tbl_try1')->insertGetId($t);      
		 */
		///$result = DB::table("tbl_try1")->select("f_data")->where("id","=",24670)->first();
		
		//print_r($data);
		
        include_once('/home/steelmin/public_html/hf.php');
        include_once('/home/steelmin/public_html/steeladmin/invoices/invoice_function_sm.php');
         //// form-data /////////////////////////////////////
         //$reciept = json_decode($request->input('recipt'));
         //// raw-data //////////////////////////////////////
		
        if($request->has('Recpt')){
        ///if($result){
			///$data = json_decode($result, true); 
			$data = json_decode($request->input('Recpt'), true);
			
			if(isset($data['logID'])){///ON IAP
				if($data['status']=='success'){
				
					$logID = $data['logID'];
					//$recieptRes = $data['receipt'];
					$reciept = $data['receipt'];
					
					$token_app = $data['tokenInApp'];
					$physical = $data['physical_id'];
					$pymDtls=$data['device_Type'];
					
					$f_currency=$data['product_currency'];
					$pymtMode='in-app purchase';
					$amtPaid=$data['Product_amount'];
					///srand($this->make_seed());
					/* if(!isset($recieptRes['receipt'])){
						$code = 1001;
						$message = "Successfully Saved";
					}else{ 
						$reciept =  $recieptRes['receipt'];*/
				
					$store=array(); 
					if(isset($reciept["in_app"]) && is_array($reciept["in_app"])){
						$t=array();$mem_id=0;$apple_id='';
						
						$result = DB::table("tbl_reg_logs")->select("memid")->where("id","=",$logID)->first();
						$mem_id = $result["memid"];
				
						$size = count($reciept["in_app"]);
						foreach($reciept["in_app"] as $k=>$v){

							$apple_id = $v["original_transaction_id"];
							$t['datepay'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							//$t['enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
							$t['apple_startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							$t['apple_enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));

							//$t['status'] = strtotime($t["apple_enddate"]) > strtotime(date("Y-m-d H:i:s")) ? "Active" : "Expired";
							$t['status'] = strtotime(date("Y-m-d", strtotime($t["apple_enddate"]))) >= strtotime(date("Y-m-d")) ? "Active" : "Expired";
							///ECHO '<pre>'.$t['status'].'--'.date("Y-m-d H:i:s", strtotime($t["apple_enddate"])).'--'.date("Y-m-d H:i:s").'--'.'</pre>';
							$t['paymentstatus']='Paid';
							$t['acc_ver_pending'] = 1;
							$t['f_currency'] = $f_currency;
							///$t['startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							$t['pymDtls'] = $pymDtls;
							$t['f_product']='MA';
							//$t['inv_no'] = "tmp_".rand();
							$t['f_tenure']='One Year';
							$t['amtPaid'] = $k == $size-1 ? $amtPaid:"";
							//$t['selected_products']='Standard';
							//$t['created_on']=date("Y-m-d H:i:s");
							$t['nb_order_no'] = $v["purchase_date_ms"];
							$t['pymtMode'] = $pymtMode;
							$t['apple_package_ID'] = $v["product_id"];
						   
						   
							
							//$result = DB::table("tbl_reg_logs")->leftJoin("tbl_members","tbl_reg_logs.memid","=","tbl_members.id")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid')->where("tbl_reg_logs.nb_order_no","=",$v["purchase_date_ms"])->where("tbl_members.apple_id","=",$apple_id)->first();//->count()
							///DB::enableQueryLog(); //
							$result = DB::table("tbl_reg_logs")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid')->where("tbl_reg_logs.nb_order_no","=",$v["purchase_date_ms"])->where("tbl_reg_logs.memid","=",$mem_id)->first();//->count()
							//dd(DB::getQueryLog()); 
							if(count($result)>0){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
								///$mem_id = $result["memid"];
								$log_id = $result["log_id"];
								$dontExpireByApple = $result["dontExpireByApple"];
								
								if($logID==$log_id){//update
									if($dontExpireByApple==0 && $t['status']=="Expired"){
										$t['status']="Expired";
										DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									}else
										$t['status']=$result["status"];///don't Expired till log date
									//DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
								}else{//insert
									/* if($result['status']=='Active' && $t['status']=='Active'){//update
										
									} */
									$t['memid'] = $mem_id;
									
									$t['selected_products']="Mobile App";
									$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
									if($resultPackages){
										$t['selected_products']='GroupID:'.$resultPackages['group_id'];
										
										$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
										if($resultPackagesCC)
											$t['selected_products']=$resultPackagesCC['id'];//Package ID
									}
									if($dontExpireByApple==0 && $t['status']=="Expired"){
										DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									}
									///$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
									///DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
									///DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
								}
								
								$t['memid'] = $mem_id;
							}else{//insert
								/* $result = DB::table("tbl_reg_logs")->select("memid")->where("id","=",$logID)->first();
								$mem_id = $result["memid"]; */
								
								
								$t['memid'] = $mem_id;
								$t['startdate'] = $t['apple_startdate'];
								$t['enddate'] = $t['apple_enddate'];
								
								$t['selected_products']="Mobile App";
								$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
								if($resultPackages){
									$t['selected_products']='GroupID:'.$resultPackages['group_id'];
									
									$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
									if($resultPackagesCC)
										$t['selected_products']=$resultPackagesCC['id'];//Package ID
								}
								//DB::enableQueryLog();
								$resultLog = DB::table("tbl_reg_logs")->select("id", "selected_products")->where("memid","=",$mem_id)->where(DB::raw("(STR_TO_DATE(created_on,'%Y-%m-%d'))"), ">=", date("Y-m-d"))->where("apple_package_ID","=",$t['apple_package_ID'])->orderBy('created_on' , 'asc')->first();
								//dd(DB::getQueryLog()); 
								//print_R($resultLog);
								if($resultLog){//update
									$log_id = $resultLog["id"];
									///$dontExpireByApple = $result["dontExpireByApple"];
									///echo $logID.'==.'.$log_id.'-'.$t['status'];
									if($logID==$log_id && $t['status']=='Active'){
										DB::table('tbl_reg_logs')->where("id", "=" , $logID)->update($t);
									
										DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
									}else{
										/* $t['created_on']=date("Y-m-d H:i:s");
										$t['f_time']=date("H:i:s");
										$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
										DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]); */
									}
									
								}/* else{
									$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
									DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
								} */
								///$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
								//DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
								
								
								///DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
							} 
						}
						
						updateTbltbl_updated_reg_logs($mem_id);
						
						if($logID){
							///$stats = "Successful Payment <br />";
							$msgsadmin ='
									<table width="600" border="0" cellspacing="0" cellpadding="0" > 
										<tr> 
											<td><img src="https://www.steelmint.com/images/logo.gif"></td>
											<td width="293">&nbsp;</td> 
										</tr> 
										<tr> 
											<td colspan="2" align="left"><p><br />Hi,<br><br><b>Membership Id : '.$mem_id.'</b> has been registered for ios app with <b>Successful Payment</b> </p> 
											</td> 
										</tr> 										
									</table>
								';
							$sender="SteelMint";
							$sender_email="info@steelmint.com";
							$sender_url=BASEURL."";
							/* $ureg_res = mysql_query("select (select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.rm) as relMngr,
										(select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.subrm) as subRelMngr from tbl_updated_reg_logs as ureg where memid=$mem_id and services in ('W','MA','S','E') limit 1");
							$ureg_row = mysql_fetch_array($ureg_res); */
							$ureg_row = DB::select("select (select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.rm) as relMngr,
										(select RM_email from tbl_rel_manager where tbl_rel_manager.id = ureg.subrm) as subRelMngr from tbl_updated_reg_logs as ureg where memid=$mem_id and services in ('W','MA','S','E') limit 1");
							
							if( $ureg_row['relMngr'] != '') 
								$rmEmail = $ureg_row['relMngr'];
							if(  $ureg_row['subRelMngr'] != '' ) 
								$rmEmail =$ureg_row['subRelMngr'];
							//sendSMMail($msgsadmin, 'mohan@theitbooth.com', "", "Registration from ".$pymtSrc, "", $sender_email, $sender, $sender_email);
							sendSMMail($msgsadmin, $rmEmail . ',accounts@steelmint.com,virendra@steelmint.com,info@steelmint.com', "", "Registration from inApp", $sender_email, $sender, $sender_email);
						}
						
						$code = 1001;
						$message = "Successfully Saved";
					}else{
						$code = 2001;
						$message = "Invalid  Request";
					}
				}else{///failure
					if($data['logID']){
						
						$userLogRes = DB::table("tbl_reg_logs")->select("memid")->where("id","=",$data['logID'])->first();
						$memid = $userLogRes["memid"];
						$userRes = DB::table("tbl_reg_logs")->select(DB::raw('(CASE WHEN send_email_to = "R" THEN email ELSE addtnl_email END) AS emailId'))->where("id","=",$memid)->first();
						
						$failedData = array(
							"paymentstatus"=>"Failed",
							"pymtMode"=>"in-app purchase",
							//"offline_attachment"=>''
							"datepay"=>'0000-00-00'
						);
						DB::table('tbl_reg_logs')->where("id" , "=" , $data['logID'])->update($failedData);
						///comments
						$failedComment = array(
							'f_date'	=>	$GLOBALS['currDate'], 
							'f_time'	=>	$GLOBALS['currTime'], 
							'comments'	=>	'iOS in-app purchase payment failed, logid:'.$data['logID'], 
							'memid'	=>	$memid, 
							'comments_for'	=>	'MA', 
							'created_by'	=>	'auto after in-app pymt failure'
						);
						
						DB::table('tbl_comments')->insert($failedComment);						
						//include_once ('/home/steelmin/public_html/hf.php');
						include_once ('/home/steelmin/public_html/mf.php');
						if($userRes['emailId'])
							linkSentAfterPymtFailureV2019($userRes['emailId'],$data['logID']);
					}
					$code = 2001;
					$message = "payment failed";
				}
				///}
			}else{///on restore and app start
				//$reciept = $data['recipt');
				
				///$recieptRes = $data['receipt'];
				$reciept = $data['receipt'];
				
				///if(!isset($recieptRes['receipt'])){
				if(!isset($data['receipt'])){
					$code = 2001;
					$message = "Invalid  Request";
				}else{
					
					$token_app = $data['tokenInApp'];
					$physical = $data['physical_id'];
					$pymDtls=$data['device_Type'];
					$pymtMode='in-app purchase';
					/* $f_currency=$data['product_currency'];
					
					$amtPaid=$data['Product_amount'];
					srand($this->make_seed()); */
					if ($data['accessToken'] && $data['accessToken']!='') {  
						$token = $data['accessToken'];
						$auth = new authentication();
						$mem_id = $auth->authToken($token,$this->appType);

						$store=array(); 
						if(isset($reciept["in_app"]) && is_array($reciept["in_app"])){
							$t=array();$apple_id='';
						   $size = count($reciept["in_app"]);
							foreach($reciept["in_app"] as $k=>$v){ 
							   $apple_id = $v["original_transaction_id"];
							   $t['datepay'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								//$t['enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
								$t['apple_startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								$t['apple_enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
							
								$t['status'] = strtotime($t["apple_enddate"]) > strtotime(date("Y-m-d H:i:s")) ? "Active" : "Expired";
								$t['paymentstatus']='Paid';
								$t['acc_ver_pending'] = 1;
								$t['f_currency'] = $f_currency;
								///$t['startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
								///$t['pymDtls'] = $pymDtls;
								$t['f_product']='MA';
								//$t['inv_no'] = "tmp_".rand();
								$t['f_tenure']='One Year';
								//$t['amtPaid'] = $k == $size-1 ? $amtPaid:"";
								//$t['selected_products']='Standard';
								$t['created_on']=date("Y-m-d H:i:s");
								$t['nb_order_no'] = $v["purchase_date_ms"];
								$t['pymtMode'] = $pymtMode;
								$t['apple_package_ID'] = $v["product_id"];

							   
								$result = DB::table("tbl_reg_logs")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid')->where("tbl_reg_logs.nb_order_no","=",$v["purchase_date_ms"])->where("memid","=",$mem_id)->first();//->count()
							   
								if($result){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
									$log_id = $result["log_id"];
									$dontExpireByApple = $result["dontExpireByApple"];
									if($dontExpireByApple==0 && $t['status']=="Expired"){
										$t['status']="Expired";
										DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
									}else
										$t['status']=$result["status"];///don't Expired till log date
									
									//DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
								}else{
									$t['memid'] = $mem_id;
									$t['startdate'] = $t['apple_startdate'];
									$t['enddate'] = $t['apple_enddate'];
									
									$t['selected_products']="Mobile App";
									$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
									if($resultPackages){
										$t['selected_products']='GroupID:'.$resultPackages['group_id'];
										
										$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
										if($resultPackagesCC)
											$t['selected_products']=$resultPackagesCC['id'];//Package ID
									}
									
									$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
									DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
									
									DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
								} 
							}
							
						
							//$inv_file = generateInvoice($company='coalmint', $reg_logs_id, 'online');
							updateTbltbl_updated_reg_logs($mem_id);
						   
						   $code = 1001;
							$message = "Successfully Saved";
						} else{
							$code = 2001;
							$message = "Invalid  Request";
						}
						
					}else{
						$code = 2100;
						$message = "Access token is invalid or has expired.";
					}
				}
			}
			
		}else{
			$code = 2001;
			$message = "Invalid  Request";
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }


    public function fromContinueOLD(Request $request){
        include_once "/home/steelmin/public_html/inc/config1.php";
        include_once('/home/steelmin/public_html/hf.php');
        include_once('/home/steelmin/public_html/steeladmin/invoices/invoice_function_sm.php');
         //// form-data /////////////////////////////////////
         //$reciept = json_decode($request->input('recipt'));
         //// raw-data //////////////////////////////////////
         
		if($request->has('logID')){///ON IAP
			$logID = $request->input('logID');
			$recieptRes = $request->input('receipt');
			
			$token_app = $request->input('tokenInApp');
			$physical = $request->input('physical_id');
			$pymDtls=$request->input('device_Type');
			
			$f_currency=$request->input('product_currency');
			$pymtMode='in-app purchase';
			$amtPaid=$request->input('Product_amount');
			///srand($this->make_seed());
			if(!isset($recieptRes['receipt'])){
				$code = 1001;
				$message = "Successfully Saved";
			}else{
				$reciept =  $recieptRes['receipt'];
				$store=array(); 
				if(isset($reciept["in_app"]) && is_array($reciept["in_app"])){
					$t=array();$mem_id=0;$apple_id='';
					$size = count($reciept["in_app"]);
					foreach($reciept["in_app"] as $k=>$v){
						$apple_id = $v["original_transaction_id"];
						$t['datepay'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
						//$t['enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
						$t['apple_startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
						$t['apple_enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));

						$t['status'] = strtotime($t["apple_enddate"]) > strtotime(date("Y-m-d H:i:s")) ? "Active" : "Expired";
						$t['paymentstatus']='Paid';
						$t['acc_ver_pending'] = 1;
						$t['f_currency'] = $f_currency;
						///$t['startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
						$t['pymDtls'] = $pymDtls;
						$t['f_product']='MA';
						//$t['inv_no'] = "tmp_".rand();
						$t['f_tenure']='One Year';
						$t['amtPaid'] = $k == $size-1 ? $amtPaid:"";
						//$t['selected_products']='Standard';
						$t['created_on']=date("Y-m-d H:i:s");
						$t['nb_order_no'] = $v["purchase_date_ms"];
						$t['pymtMode'] = $pymtMode;
						$t['apple_package_ID'] = $v["product_id"];
					   
					   
						
						$result = DB::table("tbl_reg_logs")->leftJoin("tbl_members","tbl_reg_logs.memid","=","tbl_members.id")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid')->where("tbl_reg_logs.nb_order_no","=",$v["purchase_date_ms"])->where("tbl_members.apple_id","=",$apple_id)->first();//->count()
			
						if(count($result)>0){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
							$mem_id = $result["memid"];
							$log_id = $result["log_id"];
							$dontExpireByApple = $result["dontExpireByApple"];
							
							if($logID==$log_id){//update
								if($dontExpireByApple==0 && $t['status']=="Expired"){
									$t['status']="Expired";
									DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
								}else
									$t['status']=$result["status"];///don't Expired till log date
								//DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
							}else{//insert
								/* if($result['status']=='Active' && $t['status']=='Active'){//update
									
								} */
								$t['memid'] = $mem_id;
								
								/* $t['selected_products']="Mobile App";
								$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
								if($resultPackages){
									$t['selected_products']='GroupID:'.$resultPackages['group_id'];
									
									$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
									if($resultPackagesCC)
										$t['selected_products']=$resultPackagesCC['id'];//Package ID
								} */
								
								$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
								DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
								DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
							}
							
							$t['memid'] = $mem_id;
						}else{//insert
							$result = DB::table("tbl_reg_logs")->select("memid")->where("id","=",$logID)->first();
							$mem_id = $result["memid"];
							
							$t['memid'] = $mem_id;
							$t['startdate'] = $t['apple_startdate'];
							$t['enddate'] = $t['apple_enddate'];
							
							$t['selected_products']="Mobile App";
							$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
							if($resultPackages){
								$t['selected_products']='GroupID:'.$resultPackages['group_id'];
								
								$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
								if($resultPackagesCC)
									$t['selected_products']=$resultPackagesCC['id'];//Package ID
							}
							
							DB::table('tbl_reg_logs')->where("id", "=" , $logID)->update($t);
							///$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
							//DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
							
							
							DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
						} 
					}
					
					updateTbltbl_updated_reg_logs($mem_id);
					$code = 1001;
					$message = "Successfully Saved";
				}else{
					$code = 2001;
					$message = "Invalid  Request";
				}
			}
		}else{///on restore and app start
			//$reciept = $request->input('recipt');
			$recieptRes = $request->input('receipt');
			if(!isset($recieptRes['receipt'])){
				$code = 2001;
				$message = "Invalid  Request";
			}else{
				
				$token_app = $request->input('tokenInApp');
				$physical = $request->input('physical_id');
				$pymDtls=$request->input('device_Type');
				$pymtMode='in-app purchase';
				/* $f_currency=$request->input('product_currency');
				
				$amtPaid=$request->input('Product_amount');
				srand($this->make_seed()); */
				if ($request->has('accessToken') && $request->input('accessToken')!='') {  
					$token = $request->input('accessToken');
					$auth = new authentication();
					$mem_id = $auth->authToken($token,$this->appType);

					$store=array(); 
					if(isset($reciept["in_app"]) && is_array($reciept["in_app"])){
						$t=array();$apple_id='';
					   $size = count($reciept["in_app"]);
						foreach($reciept["in_app"] as $k=>$v){ 
						   $apple_id = $v["original_transaction_id"];
						   $t['datepay'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							//$t['enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
							$t['apple_startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							$t['apple_enddate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["expires_date"])));
						
							$t['status'] = strtotime($t["apple_enddate"]) > strtotime(date("Y-m-d H:i:s")) ? "Active" : "Expired";
							$t['paymentstatus']='Paid';
							$t['acc_ver_pending'] = 1;
							$t['f_currency'] = $f_currency;
							///$t['startdate'] = date("Y-m-d H:i:s",strtotime(str_replace("\/","/",$v["purchase_date"])));
							///$t['pymDtls'] = $pymDtls;
							$t['f_product']='MA';
							//$t['inv_no'] = "tmp_".rand();
							$t['f_tenure']='One Year';
							//$t['amtPaid'] = $k == $size-1 ? $amtPaid:"";
							//$t['selected_products']='Standard';
							$t['created_on']=date("Y-m-d H:i:s");
							$t['nb_order_no'] = $v["purchase_date_ms"];
							$t['pymtMode'] = $pymtMode;
							$t['apple_package_ID'] = $v["product_id"];

						   
							$result = DB::table("tbl_reg_logs")->select('tbl_reg_logs.id as log_id', 'tbl_reg_logs.startdate', 'tbl_reg_logs.enddate', 'tbl_reg_logs.status','tbl_reg_logs.dontExpireByApple','memid')->where("tbl_reg_logs.nb_order_no","=",$v["purchase_date_ms"])->where("memid","=",$mem_id)->first();//->count()
						   
							if($result){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
								$log_id = $result["log_id"];
								$dontExpireByApple = $result["dontExpireByApple"];
								if($dontExpireByApple==0 && $t['status']=="Expired"){
									$t['status']="Expired";
									DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
								}else
									$t['status']=$result["status"];///don't Expired till log date
								
								//DB::table('tbl_reg_logs')->where("id", "=" , $log_id)->update($t);
							}else{
								$t['memid'] = $mem_id;
								$t['startdate'] = $t['apple_startdate'];
								$t['enddate'] = $t['apple_enddate'];
								
								$t['selected_products']="Mobile App";
								$resultPackages = DB::table("tbl_packages")->select("group_id")->where("apple_package_ID","=",$t['apple_package_ID'])->first();
								if($resultPackages){
									$t['selected_products']='GroupID:'.$resultPackages['group_id'];
									
									$resultPackagesCC = DB::table("tbl_packages")->select("id")->where("apple_package_ID","=",$t['apple_package_ID'])->where("currency_code","=",$f_currency)->first();
									if($resultPackagesCC)
										$t['selected_products']=$resultPackagesCC['id'];//Package ID
								}
								
								$reg_log_id = DB::table('tbl_reg_logs')->insertGetId($t);
								DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
								
								DB::table('tbl_members')->where("id" , "=" , $mem_id)->update(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
							} 
						}
						
					
						//$inv_file = generateInvoice($company='coalmint', $reg_logs_id, 'online');
						updateTbltbl_updated_reg_logs($mem_id);
					   
					   $code = 1001;
						$message = "Successfully Saved";
					} else{
						$code = 2001;
						$message = "Invalid  Request";
					}
					
				}else{
					$code = 2100;
					$message = "Access token is invalid or has expired.";
				}
			}
		}
		
		return new JsonResponse(array("status"=>array("code" => $code, "message" => $message)));
    }



    public function storeReciept(Request $request){
        include_once "/home/steelmin/public_html/inc/config1.php";
        $reciept = $request->input('recipt');
        $token_app = $request->input('tokenInApp');
		$device_id = $request->input('device_Token');

        $auth = new authentication();
        $user = $auth->authToken($token_app);
		$my_array = serialize($reciept);
		
        if($user){
                //$match = DB::table("tbl_ios_reciept")->select("id")->where("user_id","=",$user)->count();
			if(DB::table('tbl_ios_reciept')->insert(['device_id'=>$device_id,'user_id'=>$user,'reciept'=> $my_array]))
				return new JsonResponse(array("status#"=>"1","token#"=>$token_app));
			else
				return new JsonResponse(array("status#"=>"2","token#"=>$token_app));   
       } else {
			if(DB::table('tbl_ios_reciept')->insert(['device_id'=>$device_id,'reciept'=> $my_array]))
				return new JsonResponse(array("status#"=>"1","device#"=>$device_id));
			else
				return new JsonResponse(array("status#"=>"2","device#"=>$device_id));
       }
    }
	
	public function cronToUpdateDontExpireByAppleColumn(){
		$dateM2 = date('Y-m-d', strtotime(' + 2 days'));
		$dbresult = DB::table('tbl_reg_logs')
				->select('id' )			
				->where('pymtMode', "=", "in-app purchase" )
				->where('status', "=", "Active" )
				->where('apple_enddate', "=", $dateM2 )
				->where('apple_enddate', "<", 'enddate' )
				->orderBy('apple_enddate' , 'desc')
				->get();
		
		if (count($dbresult) > 0){
			foreach($dbresult as $logs){
				$t['dontExpireByApple']=1;
				DB::table('tbl_reg_logs')->where("id", "=" , $logs['id'])->update($t);
			}
		}
	}
	
  }
?>