<?php
//echo '<pre>';
//print_r($_REQUEST);

session_start();
require_once('include/db.php');
require_once('include/constant.php');
require_once('include/functions.php');

if(isset($_REQUEST['email']))
{
    $email=$_REQUEST['email'];
}
else
{
    $email='';
}

$name=$_REQUEST['name'];
$address=$_REQUEST['address'];
$mobile=$_REQUEST['mobile'];
$pwd=$_REQUEST['pwd'];
$ref_id=$_REQUEST['root_ref'];
$gender=$_REQUEST['gender'];
$dob=$_REQUEST['dob'];
$position=$_REQUEST['position'];
$refferance_id=$ref_id;
$user_join_num_of_position = 1;
//   recursive function for decide user position id
function xyz($ref_id,$position,$name,$email,$address,$mobile,$pwd,$gender,$dob,$refferance_id)
{
include 'include/db.php';
GLOBAL $user_join_num_of_position;
$position_id=$ref_id;
$virtualAmountWhileRegistration = 3000;
	
$qry="select * from registration where position_id='$ref_id' AND position='$position'";
$connection=mysqli_query($conn,$qry);
$num_row=mysqli_num_rows($connection);
if($num_row>0)
{
	while($row=mysqli_fetch_array($connection))
	{
		
		$ref_id=$row['unique_user_id'];
		$user_join_num_of_position++;  //  user position count
		return xyz($ref_id,$position,$name,$email,$address,$mobile,$pwd,$gender,$dob,$refferance_id);
	}
}
else
{
    //echo 'position id'.$position_id;
    $refferance_id=$refferance_id;
	$position=$position;
	$position_id=$position_id;
    $position_count_desc = substr(strtoupper(trim($position)),0,1).$user_join_num_of_position;
        
        //   serial wise user unique id create
        $qr2="select MAX(unique_user_id) from registration LIMIT 1";
        $con2=mysqli_query($conn,$qr2);
        if(mysqli_num_rows($con2)>0)
        {
        	while($rw=mysqli_fetch_array($con2))
        	{
        		 $xyz=$rw['MAX(unique_user_id)'];
        		 $cc=substr($xyz,1);
        		 $old_unique_id=intval($cc);  //  convert string to int
        	}
        	for ($num = $old_unique_id; $num <= $old_unique_id+1; $num++)
            $net_val=sprintf("%'.05d", $num);
            $new_unique_id= 'B'.$net_val;
        }
        //  ganerate suffle string for session security
        $session_security = md5(substr(str_shuffle(str_repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8)), 0, 8));  
        
         //   create user random transaction password
    	 $random_pwd=rand(00000,99999);
    	            
        //  insert user details
         $query="insert into registration
        (unique_user_id,user_name,user_address,user_email,user_mobile,gender,dob,user_pwd,position,position_count,position_count_desc,refferance_id,position_id,login_session,transaction_pwd,type,rank,images,active_deactive,created_date,modified_date,active_status)
        value('$new_unique_id','$name','$address','$email','$mobile','$gender','$dob','".base64_encode($pwd)."','$position','$user_join_num_of_position','$position_count_desc','$refferance_id','$position_id','$session_security','$random_pwd','user','inactive user','','0',NOW(),NOW(),'Active')";
        $con=mysqli_query($conn,$query);
        if($con)
        {
            //  set user type into session
            $_SESSION['account_type']='user';
     	    //  main session create for login purpose
    		$_SESSION['login_id']=$session_security;
    		//  unique user id stored into session
            $_SESSION['unique_user_id']=$new_unique_id;
             //  user email stored into session
            $_SESSION['user_email']=$email;
             //   login secure page redirect session create
            $_SESSION['redirect']=md5(substr(str_shuffle(str_repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 8)), 0, 8));
       	
    	       //   update position into tree table
    	       //$qry4="update tree_data set position_id='$new_unique_id' where ref_id='$position_id' and position_char='$position' ";
    	       $qry4="update tree_data ";
    	            if($position=='left')
    	            {
    	                $qry4.="set position_left='$new_unique_id' where position_id='$position_id' ";
    	            }
    	            else if($position=='right')
    	            {
    	                $qry4.="set position_right='$new_unique_id' where position_id='$position_id' ";
    	            }
    	       
    	       $connection3=mysqli_query($conn,$qry4);
    	       if($connection)
    	       {
    	           //  update member into tree data table successfully
    	       }
    	       
    		   //  insert two blank user into tree table
			   
    	       $qry3="insert into tree_data(position_id,position_left,position_right)
    	               values('$new_unique_id','','')";
    	       $connection2=mysqli_query($conn,$qry3);
    	       if($connection2)
    	       {
    	            //   two empty user added successfully
    	            //   create wallet for new user
    	            $qr11="insert into wallet_balance(balance_user_id,total_balance,total_balance_v,bv_balance) value('$new_unique_id','0',$virtualAmountWhileRegistration,'0')";
    	            $conn22=mysqli_query($conn,$qr11);
    	            if($conn22)
    	            {
    	                //  new user wallet create successfully
    	            }
    	            
    	            
    	          
    	            //   wallet section
        	       //   create transaction id
        	      /* 
        	      $transaction_id=substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 15)), 0, 15);
        	      $qry5="insert into wallet(user_idd,balance,source_user_id,source,transaction_date,transaction_id,remarks)
        	           value('$refferance_id','50','$new_unique_id','signup credit points',NOW(),'$transaction_id','')";
        	      $exe=mysqli_query($conn,$qry5);
        	       if($exe)
        	       {
        	           echo 'successfully';
        	       }
        	       */
    	            
    	            //   send details to user througn text message   
    	                
    	              /*  $message= '';
    	            
                    	$YourAPIKey='145236e8-01f8-11e9-a895-0200cd936042';
                		$From='FDSPHO';
                		$To=$mobile;
                		$Msg=$message;
                
                		### DO NOT Change anything below this line
                
                		$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';
                
                		$url = "https://2factor.in/API/R1/?module=TRANS_SMS&apikey=$YourAPIKey&to=$To&from=FDSPHO&templatename=Customer+Details&var1=:$new_unique_id&var2=:$pwd&var3=:$random_pwd"; 
                		$ch = curl_init(); 
                		curl_setopt($ch,CURLOPT_URL,$url); 
                		curl_setopt($ch,CURLOPT_POST,true); curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); curl_setopt($ch,CURLOPT_POSTFIELDS,"From=$From&To=$To&Msg=$Msg"); 
                		curl_setopt($ch, CURLOPT_USERAGENT, $agent);
                		echo curl_exec($ch); 
                		curl_close($ch);
                		*/
                		
    	            
    	            //    send email to user if its isset
				   // Skip tester email test@test.com
        	           if($email!='' && $email != 'test@test.com')
        	       {
        	            $to = $email;
                        $subject = "You have registration successfully";
                        $txt = "Your unique id is- " .$new_unique_id. 
                                "\nYour transaction password  is- ".$random_pwd.
                                "\nyour account password is- " .$pwd;
                        $headers = "From: info@fairyindia.com";
                        
                        if(mail($to,$subject,$txt,$headers))
                        {
                         echo 'successfully';
                        }
                        else
                        {
                        	//echo 'Not send';
                        }
        	       }
				   //  For tester 1111111111
                   if($mobile!='' && $mobile != '1111111111')  
                   {
                            $template = get_sms_template('REGISTRATION');
                            $replaceArray = array(
                            "[USER_NAME]"=>$name,
                            "[WEBSITE_NAME]" => WEBSITE_NAME,
                            "[UNIQUE_ID]" => $new_unique_id,
                            "[PASSWORD]" => $pwd
                            );
                       $smsText = str_replace(array_keys($replaceArray),$replaceArray,$template);
                       $checkSmsStatus = sendSmsDemo($mobile,$smsText);
                   }
                   
    	            
    	       }
    	       
        
        }
        else
        {
        	//echo '<pre>';
        	//print_r($conn);
        	echo 'err';
        }

      
}
}
xyz($ref_id,$position,$name,$email,$address,$mobile,$pwd,$gender,$dob,$refferance_id);


 
?>