<?php
namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Http\Controllers\Auth\authentication;
use DB ;

class IosFlowController extends Controller
{
    public function __construct(Request $request) {
        if($request->has('debug') && $request->input('debug') == true) {
            $this->debug = true;
        }
    }

    public function make_seed()
    {
       list($usec, $sec) = explode(' ', microtime());
       return $sec + $usec * 1000000; 
    }
    
    public function fromContinue(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 //////////////////////////////////////
         $reciept = $request->input('recipt');
         $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());
            $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['status'] = strtotime($t["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']='C';
                       $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;

                       
                       $match = DB::table("tbl_reg_logs")->leftJoin("tbl_members","tbl_reg_logs.memid","=","tbl_members.id")->select("memid")->where("tbl_reg_logs.nb_order_no","=",$t['nb_order_no'])->where("tbl_members.apple_id","=",$apple_id)->count();
                       
                       if($match>0){////DB::enableQueryLog(); //dd(DB::getQueryLog()); 
                            $result = DB::table("tbl_reg_logs")->select("memid")->where("nb_order_no","=",$t['nb_order_no'])->first();
                            $mem_id = $result["memid"];
                            $t['memid'] = $mem_id;
                       }else{
                            $store[]=$t;
                       } 
                    }
                    foreach($store as $ks){
                        if($mem_id != 0){
                            $ks['memid'] = $mem_id;
                            $reg_log_id = DB::table('tbl_reg_logs')->insertGetId($ks);
                            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]);
                        } else {
                             $mem_id = DB::table('tbl_members')->insertGetId(['physical_id'=>$physical,'device_token'=>$token_app,'apple_id'=>$apple_id]);
                             $ks['memid'] = $mem_id;
                             $reg_log_id = DB::table('tbl_reg_logs')->insertGetId($ks);
                             DB::table('tbl_reg_logs')->where("id" , "=" , $reg_log_id)->where("memid", "=" , $mem_id)->update(["first_log_id" => $reg_log_id ]);
                        }
                    }

                    //$inv_file = generateInvoice($company='coalmint', $reg_logs_id, 'online');
                    updateTbltbl_updated_reg_logs($mem_id);
                   
                    DB::table($_ENV['REFRESH_TOKEN_TABLE'])
						->where($_ENV['USER_ID'], '=', $mem_id)
						->delete();

                    //Remove User Id from gcm_device table
                    DB::table('gcm_device')
                            ->where("user_id" , "=" , $mem_id)
                            ->update(["user_id" => 0 ]);
				    
                    // Create new token
                    $refreshToken = str_random($_ENV['REFRESH_TOKEN_LENGTH']);
                    if (DB::table($_ENV['REFRESH_TOKEN_TABLE'])->insert( [  $_ENV['USER_ID']=> $mem_id , $_ENV['REFRESH_TOKEN_COLUMN'] => $refreshToken ])){
                                $auth = new authentication();
                                $token = $auth->generateToken($refreshToken);
                                if ($token) {
                                    return new JsonResponse(array("status#"=>"1","token#"=>$token));
                                }
                                else {
                                    return new JsonResponse(array("status#"=>"2","token#"=>null));
                                }
					           
                    }else {  
                      return new JsonResponse(array("status#"=>"2","token#"=>null));
				    }
                 } else {
                      return new JsonResponse(array("status#"=>"2","token#"=>null));
                 }

    } 



    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));
       }
    }
  }
?>